I2c library for C

From Tuxamito
Revision as of 13:21, 20 November 2015 by Daniel (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This library was created to make communication with I2C devices from C language. Up to know it has work fine for in Raspberry Pi boards (and similar ones!).

Download: File:I2c-driver.tar.gz

Usage

All the function calls of this library need a i2c_dev structure holding the configuration information.

struct i2c_dev {
  int fd;
  uint16_t addr;
  int tba;
};

Before any call to the library we have to set-up the I2C device address in the i2c_dev structure. The field tba allows the user to choose between 7-bit or 10-bit I2C addresses ("tba" stands for Ten Bit Address); a 0 value in tba selects 7-bit addressing, any other value selects 10-bit addressing. The address of the I2C device should be written in the addr field.

Then the provided functions in the library can be called. The first function to be called has to be i2c_dev_open to open the device descriptor and the last one, after its use the function i2c_dev_close has to be called to close the descriptor and clean the used data structures.

int i2c_dev_open(struct i2c_dev *dev, int adapter);
int i2c_dev_close(struct i2c_dev *dev);

int i2c_dev_write(struct i2c_dev *dev, uint8_t *buf, int n);
int i2c_dev_read(struct i2c_dev *dev, uint8_t *buf, int n);
int i2c_dev_wrrs(struct i2c_dev *dev, uint8_t *wbuf, int wn, uint8_t *rbuf, int rn);

Set Up I2C device

int i2c_dev_open(struct i2c_dev *dev, int adapter);

Close I2C device

int i2c_dev_close(struct i2c_dev *dev);

Write to device

int i2c_dev_write(struct i2c_dev *dev, uint8_t *buf, int n);

Read from device

int i2c_dev_read(struct i2c_dev *dev, uint8_t *buf, int n);

Combined Write/Read

int i2c_dev_wrrs(struct i2c_dev *dev, uint8_t *wbuf, int wn, uint8_t *rbuf, int rn);

The purpose of this is to allow combined write/read operations to one or more devices without releasing the bus and thus with the guarantee that the operation is not interrupted.

The hardware support for this feature is usually disable in the Rapberry Pi. To activate it execute as root:

echo 1 > /sys/module/i2c_bcm2708/parameters/combined 

Example

struct i2c_dev my_dev;

my_dev.tba  = 0;
my_dev.addr = addr;

//i2c_adapter is 0 or 1 in Raspberry Pi, depending on the model
i2c_dev_open(&my_dev, i2c_adapter);

...

i2c_dev_close(&my_dev);