RE: I2C Access with 5CSX Development Board » i2cdevice.cpp
1 |
#include "i2cdevice.h"
|
---|---|
2 |
#include <stdio.h>
|
3 |
#include <stdint.h>
|
4 |
#include <stdlib.h>
|
5 |
#include <linux/i2c-dev.h>
|
6 |
#include <sys/types.h>
|
7 |
#include <fcntl.h>
|
8 |
#include <unistd.h>
|
9 |
#include <sys/ioctl.h>
|
10 |
|
11 |
using namespace MityDSP; |
12 |
|
13 |
tcI2CDevice::tcI2CDevice(int bus, int slave_addr) |
14 |
: mnFd(-1) |
15 |
, mnBus(bus) |
16 |
, mnAddr(slave_addr) |
17 |
{
|
18 |
}
|
19 |
|
20 |
tcI2CDevice::~tcI2CDevice(void) |
21 |
{
|
22 |
if (mnFd >= 0) |
23 |
{
|
24 |
Close(); |
25 |
}
|
26 |
}
|
27 |
|
28 |
int tcI2CDevice::Open(void) |
29 |
{
|
30 |
int ret; |
31 |
char fname[100]; |
32 |
char buff[128]; |
33 |
sprintf(fname,"/dev/i2c-%d",mnBus); |
34 |
mnFd = open(fname,O_RDWR); |
35 |
if (mnFd < 0) |
36 |
{
|
37 |
sprintf(buff, "tcI2CDevice::Open:%s:",fname); |
38 |
perror(buff); |
39 |
return mnFd; |
40 |
}
|
41 |
ret = ioctl(mnFd, I2C_SLAVE, mnAddr); |
42 |
if (ret < 0) |
43 |
{
|
44 |
perror("tcI2CDevice::Open:ioctl:"); |
45 |
Close(); |
46 |
}
|
47 |
return ret; |
48 |
}
|
49 |
|
50 |
int tcI2CDevice::Close(void) |
51 |
{
|
52 |
//Return success if nothing to close
|
53 |
int retval = 0; |
54 |
|
55 |
if (mnFd >= 0) |
56 |
{
|
57 |
retval = close(mnFd); |
58 |
mnFd = -1; |
59 |
}
|
60 |
|
61 |
return retval; |
62 |
}
|
63 |
|
64 |
const char* tcI2CDevice::GetError(int /* err */) |
65 |
{
|
66 |
return "Unknown"; |
67 |
}
|