RaspberryPi: Reading I2C Inputs using C

Accessing Raspberry Pi GPIO pins with Python libraries is popular among hackers & makers. How about programming languages like C? C gives you flexibility to port code in embedded firmware/driver layer if necessary. That is why I was looking for a C library that exposes Raspberry Pi GPIO pins for application layer. I was specially interested in exploring the I2C pins and found the excellent wiringPi library.

In this post, I will show step by step on how I use wiringPi library to read from the I2C interface of a 3-axis Accelerometer+Gyroscope module. The module I used is GY521 (InvenSense MPU6050).

Hardware setup:

I have a Raspberry Pi Model B (Rev-1), GY521 (InvenSense MPU6050), breadboard & some male-female wire.

*Connect Raspberry Pi 3V3 to GY521 VCC
*Connect Raspberry Pi GND to GY521 GND
*Connect Raspberry Pi SCL to GY521 SCL
*Connect Raspberry Pi SDA to GY521 SDA

To find the Raspberry Pi GPIO pin maps, follow this guide


*Install I2C dev library. Under Raspbian, use

sudo apt-get install libi2c-dev

*Configure I2C pins using adafruit guide

*Install wiringPi using this link

*Make sure your Raspberry Pi can detect the device attached to the I2C interface. If detected, then you will see an address with below command. In my case, the address is 0x68 which is then used in the code.

i2cdetect -y 0 # Rev 1
i2cdetect -y 1 # Rev 2

*Use this sample code from my github

*Use the Makefile and type

$make i2ctest
$sudo ./i2ctest

You should now see the sensor data value in the screen.


9 thoughts on “RaspberryPi: Reading I2C Inputs using C

  1. Nice but when I tried to compile the code, I get the following error:
    /tmp/cc8j25Bn.o: In function `main’:
    12ctest.c:(.text+0x14): undefined reference to `wiringPiSetup’
    12ctest.c:(.text+0x1c): undefined reference to `wiringPiI2CSetup’
    12ctest.c:(.text+0x4c): undefined reference to `wiringPiI2CRead’
    collect2: ld returned 1 exit status
    : recipe for target ’12ctest’ failed
    make: *** [12ctest] Error 1

    Any ideas?


  2. Hi, thanks for the tutorial ! It was very helpful. How can I get (0-255) value when I try to measure an analog input value ? I am only getting (0-5) using your code. I am using a potentiometer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s