User avatar
Posts: 70
Joined: Wed Nov 30, 2011 8:29 pm

Example I2C Code

Sun Jun 10, 2012 4:47 pm

Has anyone an example of actual working 'C' code to write to the I2C port on the Raspi. I have built my hardware and can set/clear GPIO bits , pwm etc but could do with some help in sending and receiving data to/from I2C devices. I am new to 'C' (and cant do Python yet). As I am portng an exiting Java app I am actually using Java with JNI to access hardware using a hacked version of the WiringPi code. All help gratefully received.

Posts: 10
Joined: Mon Feb 27, 2012 8:34 pm
Location: Kent, UK

Re: Example I2C Code

Mon Jun 11, 2012 6:51 pm

To start with, use bootc's kernel and have a look under /sys/class/i2c-adapter/i2c-0. (i2c-0 is on the GPIO header, there's also i2c-1 which is a separate I2C bus on the camera connector.) To use existing in-kernel drivers the device will need to be registered, for example

Code: Select all

echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-0/new_device
and a new directory should appear under /sys/class/i2c-adapter/i2c-0 corresponding to the device address. Also, install i2c-tools and load the i2c-dev module and you can play with some command-line tools.

There's some C code in the kernel docs.

Posts: 1
Joined: Thu Jun 21, 2012 10:29 am

Re: Example I2C Code

Thu Jun 21, 2012 10:33 am

There is example code and a setup guide here. ... amples.htm
Shouldnt take much to adapt them to whatever you need to use them for.

Posts: 192
Joined: Sun Dec 25, 2011 5:25 pm
Location: Edinburgh, UK
Contact: Website

Re: Example I2C Code

Thu Jun 21, 2012 11:25 am

fulburncams wrote:Hi
Has anyone an example of actual working 'C' code to write to the I2C port on the Raspi.
I wrote some brief notes on what I did to get an I2C RTC running on th Pi, using both kernel drivers and user code accessing registers. ... clock-rtc/

The C code implements the systohc and hctosys functions of hwclock directly with BSC0 registers.

Posts: 3
Joined: Tue Sep 04, 2012 3:30 pm

Re: Example I2C Code

Wed Oct 03, 2012 12:37 pm


I have succeeded in basic I2C control with java.

Look at this post: ... 73#p187073


Return to “Interfacing (DSI, CSI, I2C, etc.)”

Who is online

Users browsing this forum: No registered users and 17 guests