Skip to content

Instantly share code, notes, and snippets.

@dprilutskii
Last active July 18, 2022 08:39
Show Gist options
  • Save dprilutskii/7c29d434fd6cb5a7848216b21aa7cdc5 to your computer and use it in GitHub Desktop.
Save dprilutskii/7c29d434fd6cb5a7848216b21aa7cdc5 to your computer and use it in GitHub Desktop.
Raspberry Pi example for I2C operations
#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "i2c.h"
/* Init I2Cdevice */
int i2c_init( char fdname[40], int addr )
{
int fd = open(fdname, O_RDWR);
if( fd < 0 )
{
printf("Failed to open the bus\r\n\r");
return fd;
}
printf("Open i2c \"%s\"...\r\n\r", fdname);
if( ioctl(fd, addr) < 0 )
{
printf("Failed to acquire bus access and/or talk to slave for address %x\r\n\r", addr_error);
return fd;
}
printf("I2C address init...\r\n\r");
return fd;
}
/* Read n bytes */
int i2c_read(int fd, int add1, int add2, int nbytes, unsigned char *buf)
{
int n;
#ifdef DEBUG
printf("Reading %d bytes...\r\n\r", nbytes);
#endif
if( read(fd, buf, nbytes) != nbytes )
{
fprintf(stderr, "Error reading %i bytes\r\n\r", nbytes);
}
else
{
#ifdef DEBUG
printf("[ OK ] | ");
for (n = 0; n < nbytes; n++)
{
printf("r_0x%0*x ", 2, *buf++);
}
printf("\r\n\r");
#endif
}
return nbytes;
}
/* Write n bytes */
void i2c_write(int fd, int add1, int add2, int nbytes, unsigned char value[2])
{
int n, i;
unsigned char buf[10];
buf[0] = add1;
buf[1] = add2;
if (nbytes >= 1)
{
buf[2] = value[0];
}
if (nbytes >= 2)
{
buf[3] = value[1];
}
if (nbytes >= 3)
{
buf[4] = value[2];
}
if (nbytes >= 4)
{
buf[5] = value[3];
}
#ifdef DEBUG
printf("Write (address | data): %02X%02X | ", buf[0], buf[1]);
for (i = 0; i < nbytes; i++)
{
printf("%02X ", buf[i+2]);
}
printf("\r\n\r");
#endif
if( write(fd, buf, nbytes+2) != nbytes+2 )
{
printf("Error writing %i bytes\r\n\r", nbytes);
}
#ifdef DEBUG
else
{
printf("Write done succesfully\r\n\r");
}
#endif
}
#ifndef RPI_I2C_H
#define RPI_I2C_H
#ifdef __cplusplus
extern "C" {
#endif
/* Init I2Cdevice */
int i2c_init(char filename[40], int addr);
/* Read n bytes */
int i2c_read(int fd, int add1, int add2, int nbytes, unsigned char *buf);
/* Write n bytes */
void i2c_write(int fd, int add1, int add2, int nbytes, unsigned char *buf);
#ifdef __cplusplus
}
#endif
#endif /* RPI_I2C_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment