andrewm@0: /* andrewm@0: * I2c.h andrewm@0: * andrewm@0: * Created on: Oct 14, 2013 andrewm@0: * Author: Victor Zappi andrewm@0: */ andrewm@0: andrewm@0: #ifndef I2C_H_ andrewm@0: #define I2C_H_ andrewm@0: andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: andrewm@0: #define MAX_BUF_NAME 64 andrewm@0: andrewm@0: using namespace std; andrewm@0: andrewm@0: andrewm@0: class I2c andrewm@0: { andrewm@0: andrewm@0: protected: andrewm@0: int i2C_bus; andrewm@0: int i2C_address; andrewm@0: int i2C_file; andrewm@0: andrewm@0: public: andrewm@0: int initI2C_RW(int bus, int address, int file); andrewm@0: virtual int readI2C() = 0; andrewm@0: int closeI2C(); andrewm@0: andrewm@0: virtual ~I2c(); andrewm@0: andrewm@0: }; andrewm@0: andrewm@0: andrewm@0: inline int I2c::initI2C_RW(int bus, int address, int fileHnd) andrewm@0: { andrewm@0: i2C_bus = bus; andrewm@0: i2C_address = address; andrewm@0: i2C_file = fileHnd; andrewm@0: andrewm@0: // open I2C device as a file andrewm@0: char namebuf[MAX_BUF_NAME]; andrewm@0: snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", i2C_bus); andrewm@0: andrewm@0: if ((i2C_file = open(namebuf, O_RDWR)) < 0) andrewm@0: { andrewm@0: cout << "Failed to open " << namebuf << " I2C Bus" << endl; andrewm@0: return(1); andrewm@0: } andrewm@0: andrewm@0: // target device as slave andrewm@0: if (ioctl(i2C_file, I2C_SLAVE, i2C_address) < 0){ andrewm@0: cout << "I2C_SLAVE address " << i2C_address << " failed..." << endl; andrewm@0: return(2); andrewm@0: } andrewm@0: andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: andrewm@0: andrewm@0: inline int I2c::closeI2C() andrewm@0: { andrewm@0: if(close(i2C_file)>0) andrewm@0: { andrewm@0: cout << "Failed to close file "<< i2C_file << endl; andrewm@0: return 1; andrewm@0: } andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: andrewm@0: inline I2c::~I2c(){} andrewm@0: andrewm@0: andrewm@0: #endif /* I2C_H_ */