Protocols / I2C

Examples

Command-line probing

# scan bus 1 for responding addresses
i2cdetect -y 1

# read register 0x0F from device at address 0x68 on bus 1
i2cget -y 1 0x68 0x0f

# write 0x01 to register 0x10 on the same device
i2cset -y 1 0x68 0x10 0x01

Linux userspace — i2c-dev

#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>

int fd = open("/dev/i2c-1", O_RDWR);
ioctl(fd, I2C_SLAVE, 0x68);   // target address, no ioctl per-transfer needed after this

uint8_t reg = 0x0F;
write(fd, &reg, 1);          // write the register pointer
uint8_t value;
read(fd, &value, 1);         // repeated-START read of that register
What I learned

Plain write() then read() on an i2c-dev fd does not guarantee a repeated START between them on every driver — for guaranteed repeated-START semantics, use the I2C_RDWR ioctl with an struct i2c_rdwr_ioctl_data combining both messages in one call.