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 public:
31  ssize_t readBytes(void* buf, size_t count);
32  ssize_t writeBytes(const void* buf, size_t count);
33  I2c(){};
34  I2c(I2c&&) = delete;
35  int initI2C_RW(int bus, int address, int file);
36  int closeI2C();
37 
38  virtual ~I2c();
39 };
40 
41 
42 inline int I2c::initI2C_RW(int bus, int address, int fileHnd)
43 {
44  i2C_bus = bus;
45  i2C_address = address;
46  i2C_file = fileHnd;
47 
48  // open I2C device as a file
49  char namebuf[MAX_BUF_NAME];
50  snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", i2C_bus);
51 
52  if ((i2C_file = open(namebuf, O_RDWR)) < 0)
53  {
54  fprintf(stderr, "Failed to open %s I2C Bus\n", namebuf);
55  return(1);
56  }
57 
58  // target device as slave
59  if (ioctl(i2C_file, I2C_SLAVE, i2C_address) < 0){
60  fprintf(stderr, "I2C_SLAVE address %#x failed...", i2C_address);
61  return(2);
62  }
63 
64  return 0;
65 }
66 
67 
68 
69 inline int I2c::closeI2C()
70 {
71  if(i2C_file > 0) {
72  if(close(i2C_file) > 0)
73  return 1;
74  else
75  i2C_file = -1;
76  }
77  return 0;
78 }
79 
80 inline ssize_t I2c::readBytes(void *buf, size_t count)
81 {
82  return read(i2C_file, buf, count);
83 }
84 
85 inline ssize_t I2c::writeBytes(const void *buf, size_t count)
86 {
87  return write(i2C_file, buf, count);
88 }
89 
90 inline I2c::~I2c(){}
Definition: I2c.h:23
int write(const std::string &filename, float *buf, unsigned int channels, unsigned int frames, unsigned int samplerate)
Definition: AudioFileUtilities.cpp:79