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