Use GPIO pins from userspace


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. Each chip has a sub-directory in /sys/class/gpio/ named gpiochip*. These directories contain (at least) two files: label and base. The first - label - contains the name of the PIO controller which correspons to pioA (/sys/class/gpio/gpiochip0), pioB (/sys/class/gpio/gpiochip32) and pioC (/sys/class/gpio/gpiochip64) on latest kernels. Each controller is covering 32 GPIOs. The file base contains the base offset of the chip. This offset has to be added to the requested PIN number (e.g. PB29 with base = 32 becomes PIN ID 61).

Note: Older root file systems such as Debian Lenny (formerly used on NanosG20) may have other namings and base adresses. For NanosG20, it was A, B, C on bases 32, 64, 96.

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 (assuming base = 64):

echo 93 > /sys/class/gpio/export

As mentioned above, PIOB is represented by one of the chips /sys/class/gpio/gpiochip*. So, if 64 is the base offset for all GPIOs belonging to PIOB, the ID written to export results from the base offset 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.

Note: On NanosG20 with Debian Wheezy (kernel 3.4.85), PB29 is PIN ID 61 (PIOB base is 32).


You decide whether a pin is an input or an output by writing in/out to /sys/class/gpio/gpio[ID]/direction.
Consider 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.


This example sets PB29 to low level.

cat /sys/class/gpio/gpiochip64/label

cat /sys/class/gpio/gpiochip64/base

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