3

I have a Raspberry Pi model B with Raspbian and a Busware SD0 cape.
The SD0 has an RTC that can be read via the I2C bus. I want set the time and date of the Raspberry Pi because it is not always connected to the internet so the time can't be set via NTP.

Is it possible to use I2C without using "external" libraries like WiringPi (like you can use the UART via a Linux kernel module)?

n.st
  • 526
  • 4
  • 11
Doan
  • 133
  • 1
  • 1
  • 6

3 Answers3

7

The kernel has an API for SMBus/I2C. You just have to include a couple of headers:

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

There's no library that needs linking. I've used this to write C++ based interfaces to various I2C sensors, I'm sure it can be made to work with an RTC. The API isn't the complicated part, it's figuring out how to use it in relation to a datasheet.

I did notice that sometimes that using a read() or write() on the file descriptor in a manner that should have duplicated an i2c_smbus function did not produce the same result. I mention this because if one method does not seem to work, try the other.

goldilocks
  • 60,325
  • 17
  • 117
  • 234
4

There is no need to use a third party library to access I2C.

Just search for Linux I2C to find code examples.

Here is a Pi example of mine to read an ADXL345 accelerometer via I2C. Note, this code defaults to bus 0.

joan
  • 71,852
  • 5
  • 76
  • 108
1

An answer from 7 years later:

Currently (2023.4), you'd better to use a library libi2c to alleviate I2C development, instead of fully using ioctls and linux/i2c.h. Actually it is a shallow API wrapper for the I2C/SMBus declaration in linux kernel.

Edit:

You even don't need any libraries, it is actually integrated inside the Linux I2C driver if your device conforms to the SMBus behavior. What you need is only:

  • Open the i2c file device by open("/dev/i2c-X", O_RDWR ).
  • Set the current using slave address by fcntl(fd, I2C_SLAVE, YOUR_SLAVE_ADDRESS). The macro I2C_SLAVE is defined in linux/i2c-dev.h.
  • Perform simple read and write on the file descriptor. Corresponding SMBus transaction is automatically performed by underlying Linux I2C driver.

These operations are enough for operating all functions of BH1750 ambient light sensor.

jiandingzhe
  • 207
  • 2
  • 10