libi2cd  1.0.3
Linux kernel I2C character device library
libi2cd Documentation

libi2cd provides a simple and straightforward API for accessing I2C devices from userspace. It relies on the i2c-dev Linux kernel module and is intended to complement existing tools and libraries, such as those provided by i2c-tools. The design for libi2cd was inspired by libgpiod; it provides both high- and low-level access to the underlying ioctl requests and has no dependencies apart from the standard C library.

libi2cd development is hosted on GitHub. A code coverage report is also available.

Getting Started

libi2cd's main data structures and functions are documented in the Main API module. Most uses of the API are straightforward: an I2C character device handle is first created by calling i2cd_open(), which is then passed to supporting functions followed by a call to i2cd_close() to close the handle and free associated memory. A set of register access functions are also available, which are documented in the Register Access module.

The following example demonstrates reading bytes from a fictitious slave device located at address 0x20:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <i2cd.h>
int main(void)
{
struct i2cd *dev;
uint8_t buf[8];
size_t i;
/* Open I2C character device */
dev = i2cd_open("/dev/i2c-0");
if (dev == NULL) {
perror(NULL);
return EXIT_FAILURE;
}
/* Read bytes from slave address 0x20 */
if (i2cd_read(dev, 0x20, buf, sizeof(buf)) < 0) {
perror(NULL);
i2cd_close(dev);
return EXIT_FAILURE;
}
for (i = 0; i < sizeof(buf); i++)
printf("[%zu] 0x%02x\n", i, buf[i]);
/* Close character device handle */
i2cd_close(dev);
return EXIT_SUCCESS;
}

For more advanced uses, the i2cd_get_functionality() and i2cd_transfer() functions may be called to get the adapter functionality mask and to transfer one or more low-level messages, respectively.

Care should be taken if the character device handle is shared between threads as libi2cd is not inherently thread-safe. Calls using the same handle should be restricted to a single thread or synchronized using a mutual exclusion mechanism.

License

libi2cd is distributed under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or any later version. See COPYING for more details.

i2cd_close
void i2cd_close(struct i2cd *dev)
Close an I2C character device handle and free associated memory.
i2cd_read
int i2cd_read(struct i2cd *dev, uint16_t addr, void *buf, size_t len)
Read bytes from a slave device.
i2cd_open
struct i2cd * i2cd_open(const char *path)
Open the I2C character device specified by path.
i2cd
Handle to an I2C character device.