Bela
Real-time, ultra-low-latency audio and sensor processing system for BeagleBone Black
 All Classes Files Functions Variables Typedefs Macros Groups
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-dev.h>
19 // heuristic to guess what version of i2c-dev.h we have:
20 // the one installed with `apt-get install libi2c-dev`
21 // would conflict with linux/i2c.h, while the stock
22 // one requires linus/i2c.h
23 #ifndef I2C_SMBUS_BLOCK_MAX
24 // If this is not defined, we have the "stock" i2c-dev.h
25 // so we include linux/i2c.h
26 #include <linux/i2c.h>
27 typedef unsigned char i2c_char_t;
28 #else
29 typedef char i2c_char_t;
30 #endif
31 #include <sys/ioctl.h>
32 #include <stropts.h>
33 
34 #define MAX_BUF_NAME 64
35 
36 class I2c
37 {
38 
39 protected:
40  int i2C_bus;
41  int i2C_address;
42  int i2C_file;
43 
44 public:
45  int initI2C_RW(int bus, int address, int file);
46  virtual int readI2C() = 0;
47  int closeI2C();
48 
49  virtual ~I2c();
50 
51 };
52 
53 
54 inline int I2c::initI2C_RW(int bus, int address, int fileHnd)
55 {
56  i2C_bus = bus;
57  i2C_address = address;
58  i2C_file = fileHnd;
59 
60  // open I2C device as a file
61  char namebuf[MAX_BUF_NAME];
62  snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", i2C_bus);
63 
64  if ((i2C_file = open(namebuf, O_RDWR)) < 0)
65  {
66  fprintf(stderr, "Failed to open %s I2C Bus\n", namebuf);
67  return(1);
68  }
69 
70  // target device as slave
71  if (ioctl(i2C_file, I2C_SLAVE, i2C_address) < 0){
72  fprintf(stderr, "I2C_SLAVE address %#x failed...", i2C_address);
73  return(2);
74  }
75 
76  return 0;
77 }
78 
79 
80 
81 inline int I2c::closeI2C()
82 {
83  if(close(i2C_file)>0)
84  {
85  fprintf(stderr, "Failed to close file %d\n", i2C_file);
86  return 1;
87  }
88  return 0;
89 }
90 
91 
92 inline I2c::~I2c(){}
93 
94 
95 #endif /* I2C_H_ */
Definition: I2c.h:36