I2c.h
1 /*
2  * I2c.h
3  *
4  * Created on: Oct 14, 2013
5  * Author: Victor Zappi
6  */
7 
8 #ifndef I2C_H_
9 #define I2C_H_
10 
11 #include <iostream>
12 #include <iomanip>
13 #include <string>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <linux/i2c.h>
19 #include <linux/i2c-dev.h>
20 #include <sys/ioctl.h>
21 #include <stropts.h>
22 
23 #define MAX_BUF_NAME 64
24 
25 using namespace std;
26 
27 
28 class I2c
29 {
30 
31 protected:
32  int i2C_bus;
33  int i2C_address;
34  int i2C_file;
35 
36 public:
37  int initI2C_RW(int bus, int address, int file);
38  virtual int readI2C() = 0;
39  int closeI2C();
40 
41  virtual ~I2c();
42 
43 };
44 
45 
46 inline int I2c::initI2C_RW(int bus, int address, int fileHnd)
47 {
48  i2C_bus = bus;
49  i2C_address = address;
50  i2C_file = fileHnd;
51 
52  // open I2C device as a file
53  char namebuf[MAX_BUF_NAME];
54  snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", i2C_bus);
55 
56  if ((i2C_file = open(namebuf, O_RDWR)) < 0)
57  {
58  cout << "Failed to open " << namebuf << " I2C Bus" << endl;
59  return(1);
60  }
61 
62  // target device as slave
63  if (ioctl(i2C_file, I2C_SLAVE, i2C_address) < 0){
64  cout << "I2C_SLAVE address " << i2C_address << " failed..." << endl;
65  return(2);
66  }
67 
68  return 0;
69 }
70 
71 
72 
73 inline int I2c::closeI2C()
74 {
75  if(close(i2C_file)>0)
76  {
77  cout << "Failed to close file "<< i2C_file << endl;
78  return 1;
79  }
80  return 0;
81 }
82 
83 
84 inline I2c::~I2c(){}
85 
86 
87 #endif /* I2C_H_ */
Definition: I2c.h:28