Introduction: Reading I2C Inputs in Raspberry Pi Using C

Originally posted in http://lilyhack.wordpress.com/2014/07/25/raspberry...

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).

Step 1: 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

Step 2: Workflow

*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.

Comments

author
prayag nao (author)2016-12-14

Hello everyone
You can find a solution here
https://www.instructables.com/id/PIR-Sensor-Interfacing-With-Raspberry-Pi/

author
VicenteK (author)2016-07-05

This might be a little late, but for those wondering, here is the github link: https://github.com/nahidalam/raspberryPi/blob/master/i2ctest.c

author
VicenteK (author)2016-07-05

This might be a little late, but for those wondering, here is the github link: https://github.com/nahidalam/raspberryPi/blob/master/i2ctest.c

author
VicenteK (author)2016-07-05

This might be a little late, but for those wondering, here is the github link: https://github.com/nahidalam/raspberryPi/blob/master/i2ctest.c

author
le_barbu (author)2016-01-12

Hey guys, I was stuck on that for a long time and I found out that the solution was sooooooooo simple! I wrote an article about it, with every step, the code etc.

https://en.causeyourestuck.io/2015/12/28/gy-521-on-raspberry-pi-with-c/

author
remcog1 (author)2015-10-12

Hey there, I might not see it but the following line:

"Use this sample code from my github" does not contain a link, could you add the link to this instructable?

author
seamster (author)2014-11-05

Thanks for sharing these great Raspberry Pi tips!