Use GPIO pins from userspace

Introduction

This HOWTO refers to the GPIO SYSFS interface. This interface is supported by your kernel from version 2.6.30 on. It allows access to GPIO pins in an easy way.

On AT91SAM9G20 three gpiochips are available in /sys/class/gpio. These chips correspond to PIOA (/sys/class/gpio/gpiochip32), PIOB (/sys/class/gpio/gpiochip64) and PIOC (/sys/class/gpio/gpiochip96) each covering 32 GPIOs.

Note: Before a pin can be used, it has to be exported by the interface.

Exporting a GPIO

To export a GPIO you need to write it's ID to /sys/class/gpio/export.
For example if you like to export PB29:

echo 93 > /sys/class/gpio/export

As mentioned above, PIOB is represented by /sys/class/gpio/gpiochip64. So 64 is the base ID for all GPIOs belonging to PIOB. The ID written to export results from the base ID incremented by the number of the desired port pin.

After exporting a GPIO it is available under /sys/class/gpio/gpio[ID] (/sys/class/gpio/gpio93 for PB29) and can be set up and used. If you don't need a pin any longer you can release it by writing it's id to /sys/class/gpio/unexport.

Configuration

You decide whether a pin is an input or an output by writing in/out to /sys/class/gpio/gpio[ID]/direction.
Consider http://www.kernel.org/doc/Documentation/gpio.txt to get a deeper look into the whole GPIO system. It contains also a description of the API for use in programs.

Value of a GPIO

A GPIO's value can be read or set by accessing the file /sys/class/gpio/gpio[ID]/value. If it configured as output writing 1 will produce a high, 0 a low level. Read values are interpreted the same way.

Example

This example sets PB29 to low level. As already described PB29 has the ID 93.

echo 93 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio93/direction
echo 0 > /sys/class/gpio/gpio93/value