[Howto] Raspberry Pi + I²C + MCP23017 + C (minimal example)

posted in: computer, electronics | 0

minimal working example: read data from MCP23017-register and print it to screen.

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

int main(){

//open I2C-bus for reading and writing
int file = open("/dev/i2c-1", I2C_RDWR);

//set I2C-slave-adress to 0x20
ioctl(file, I2C_SLAVE, 0x20);

//read data at register 0x14
__u8  reg = 0x14;
__s32 res = i2c_smbus_read_word_data(file, reg);

//print data to screen
printf("Data read: %d\n", res);