Accessing GPIO

From InCircuit
Jump to: navigation, search

To access a given GPIO from Userspace, the Kernel's sysfs provides a suitable interface. This can be found within /sys/class/gpio on a running Board.

All GPIOs are numbered consecutively. On AT91SAM9G45 Port A starts at Pin 32, Port B at Pin 64, Port C at Pin 96 and so on. Each Port consists of 32 Pins. The following example will use GPIO 144, corresponding to Port PD16 on an ICnova AT91SAM9G45.

Usually the Pins on the Processor are multiplexed by different hardwaremodules and a GPIO-Controller. If the Pin is controlled by a specific hardwaremodule, it can't be used as a GPIO in parrallel and it can't be exported.

Exporting and accessing a specific Pin

The following commands have to be executed within the interface-directory (or it must be preceeding every file). You may want to change here by entering

 $ cd /sys/class/gpio

To export a Pin to userspace, the corresponding Pin-number must be written to the file export ASCII-encoded. Afterwards a new directory will appear, giving access to this particular Pin. If the Pin can't be exported, no directory will be created. The following commands will export the Pin 144 and change into the new directory.

 $ echo 144 > export  
 $ cd gpio144

Changing the Pins direction

The file direction controls the direction of the Pin. It can have the states in and out. Reading this file will return the corresponding string. By writing either string, the direction will be set correspondingly. The following example will first read the direction of the pin and set it to output afterwards.

 $ cat direction
 $ echo out > direction

Getting and setting the Pins state

The file value controls the state of the corresponding Pin. Usally this changes between 0 and 1. These values can be read or written to this file as ASCII-characters. If the Pin is set to be input, it's value wont change, if another value is set. The following example will first read the current state (low) and set it to high afterwards.

 $ cat value
 $ echo 1 > value
Personal tools