Example I2C Code

5 posts
by fulburncams » 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.
User avatar
Posts: 70
Joined: Wed Nov 30, 2011 8:29 pm
by DavidK » 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: 10
Joined: Mon Feb 27, 2012 8:34 pm
Location: Kent, UK
by bigchip » Thu Jun 21, 2012 10:33 am
There is example code and a setup guide here.
http://www.robot-electronics.co.uk/htm/ ... amples.htm
Shouldnt take much to adapt them to whatever you need to use them for.
Posts: 1
Joined: Thu Jun 21, 2012 10:29 am
by ksangeelee » 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.

http://www.susa.net/wordpress/2012/06/r ... clock-rtc/

The C code implements the systohc and hctosys functions of hwclock directly with BSC0 registers.
Posts: 192
Joined: Sun Dec 25, 2011 5:25 pm
Location: Edinburgh, UK
by rotok » Wed Oct 03, 2012 12:37 pm

I have succeeded in basic I2C control with java.

Look at this post:

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