Sysfs exports information about devices and drivers from the kernel device model to userspace. Gpio-sysfs is the prefered method for accessing gpio from userspace. It deals with one pin at a time and works in means of reading and writing to files for control.
The control files for each gpio chip is contained within '/sys/class/gpio/'
~ # ls /sys/class/gpio/ export gpiochip231 gpiochip235 gpiochip240 gpiochip248 unexport
To begin with there is only two files 'export' and 'unexport' and a folder for each gpio, each gpio has an ID number.
In each folder there are files that contains information about the chip:
~ # ls /sys/class/gpio/gpiochip231/ base label ngpio subsystem uevent
- 'base' contains the ID of the chip, i.e. for gpiochip231, the ID is 231
~ # cat /sys/class/gpio/gpiochip231/base 231
- 'label' contains the address (so that you are able to identify which gpio you are dealing with)
~ # cat /sys/class/gpio/gpiochip231/label /plb@0/gpio@81400000
- 'ngpio' contains the number of gpio pins available
In order to get access to a GPIO pin it is necessary to export it using the export file:
echo NN > /sys/class/gpio/export
Where NN is the base of the GPIO chip plus the pin number, i.e. for pin0 of gpiochip231 NN=231, for pin1 NN=232, etc.
echo 231 > /sys/class/gpio/export echo 232 > /sys/class/gpio/export
This gives access to pin0 and pin1.
When a pin is exported, a folder is created: '/sys/class/gpio/gpioNN'. Within such a folder you have the control files for the pin, 'direction' and 'value'
~ # ls /sys/class/gpio/gpio231/ direction subsystem uevent value
Example, setting direction of pin0 as output:
echo out > /sys/class/gpio/gpio231/direction
Possible commands for direction:
high Set GPIO to an output with a starting value of 1 low Set GPIO to an output with a starting value of 0 out Same as low in Set GPIO to an input
Example, setting value of a pin0 to 1, then reading the value:
echo 1 > /sys/class/gpio/gpio231/value cat /sys/class/gpio/gpio231/value 1
sig phys NN TDI -> pin6 -> 231 TMS -> pin4 -> 232 TDO -> pin3 -> 233 TCK -> pin1 -> 234