Saturday, April 13, 2013

Simple way to access GPIO on Raspberry PI

Got yourself a Raspberry Pi and you are using it as a cheap Linux box or Multimedia Center? Wanna play with electronics and interface your Pi with Arduino shields? So you have to learn how to control the GPIO (General Purpose Input Output) port of your Pi.

If you programming in C/C++ there is WiringPI. It is a library that provides an Arduino-like API. If you are using Python you can use Adafruit's library.

But if you do not want to install any library or if you are using another language besides C or Python? Fortunately the RPi kernel exports the GPIO pins to sysfs.

Sysfs, like the procfs, is a Linux pseudo-filesystem. It looks like regular files and directories. You can read them, write to them... But if you do a ls -l  you are going to see that they have zero size. When you read or write to a file, the calls are intercepted by the Linux Virtual File System layer which delivers the calls to the proper implementation of file system. So if the file is in a ext3 partition, the ext3 file system drive is called. In our case the calls are passed to the sysfs implementation which will configure the GPIO ports.

Before telling you how to use  the GPIO pins from sysfs, let me show you a simple schematic to test the GPIO:


The pin 24 (GPIO8) is connect to the LED. The LED is connect to an 1 kilo ohms pull down resistor that will protect our LED and Pi. The resistor is connected to pin 25 (GND). I want to control whether the LED will be lit. So I need the GPIO8 to output 1 ( or 5 volts) to lit the LED.

First we need to set GPIO8 to be a output pin. I am going to use shell script for that.

#We need to be the super user to use the gpio
sudo -i

#Set GPIO 8 to output 
echo "8" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio8/direction

To blink the LED we just need to write ones and zeros to the GPIO8:
while :
do 
    echo "1" >  /sys/class/gpio/gpio8/value
    sleep 1
    echo "0" > /sys/class/gpio/gpio8/value
    sleep 1
done

One you are done you must free the pin

echo "8" > /sys/class/gpio/unexport


Here is a video of how it works on real life: