Working With I2C using c++

n this article, I will explain C++ libraries that enable to work with these protocols on a Raspberry Pi. For each protocol, I researched useable libraries, and give a short explanation and code exampl

I2C can be supported with the help of the SMBus protocol, which is described as a specific variant of the I2C bus. This protocol is available as Linux Kernel module. To use it, you need to configure your Raspberry Pi. In a terminal, run raspi-config, select 3 Interfacing Options and P5 I2C.

Following the code example from kernel.org, you will need to open the device file that represents the connected I2C device, and then send SMBus commands by writing to the devices registers.

// SOURCE: https://www.kernel.org/doc/Documentation/i2c/dev-interface */
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>

int file;
int adapter_nr = 2;
char filename[20];

snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
  exit(1);
}

  int addr = 0x40;

if (ioctl(file, I2C_SLAVE, addr) < 0) {
  exit(1);
}

__u8 reg = 0x10;
__s32 res;
char buf[10];

res = i2c_smbus_read_word_data(file, reg);
if (res < 0) {
  /* ERROR HANDLING: i2c transaction failed */
} else {
  /* res contains the read word */
}

buf[0] = reg;
buf[1] = 0x43;
buf[2] = 0x65;
if (write(file, buf, 3) != 3) {
  /* ERROR HANDLING: i2c transaction failed */
}

Last updated