From the version 4.8, the Linux kernel introduces a new user space API based on character devices for managing and controlling GPIOs (General-Purpose Input/Output).
The gpiod package provides commands to access the gpio, and also a C library to handle gpio devices.
The following guide shows how to use the new userspace char device driver and API (gpiod).The new character device and API makes use of /dev/gpiochip devices.
ls /dev/gpiochip*
/dev/gpiochip0
/dev/gpiochip1
/dev/gpiochip2
/dev/gpiochip3
/dev/gpiochip4
/dev/gpiochipX corresponds to a GPIO controller device, a controller of a bank of GPIOs.
gpiodetect
To discover gpio controller devices and how many GPIOs are attached.
# on a imx8mm board
gpiodetect
gpiochip0 [30200000.gpio] (32 lines)
gpiochip1 [30210000.gpio] (32 lines)
gpiochip2 [30220000.gpio] (32 lines)
gpiochip3 [30230000.gpio] (32 lines)
gpiochip4 [30240000.gpio] (32 lines)
gpioinfo
To list the information for the gpio lines per bank.
# to get line info of gpiochip0 controller
gpioinfo -c gpiochip0
gpiochip0 - 32 lines:
line 0: "SODIMM_43" "cd" input active-low [used]
line 1: "SODIMM_45" "Wake-Up" input active-high [used]
line 2: "SODIMM_135" unused input active-high
line 3: "SODIMM_22" unused input active-high
gpioinfo 5
line 0: "BTN1" unused output active-high
line 1: "LED1" unused output active-high
line 2: "LED2" unused output active-high
gpiofind
# to find the controller and the line index of the gpio line name “SODIMM_135”
gpiofind SODIMM_135
gpiochip0 2
gpioset
The gpioset command can be used to set a GPIO line. In the example below LED2 will turn on.
gpioset 5 2=1
gpioget
The gpioget command can be used to read the value of a GPIO line. In the example below the value of BTN1 will be read.
gpioget 5 0
gpiomon
Wait for events on GPIO line
gpiomon 0 13
event: FALLING EDGE offset: 13 timestamp: [1570281706.661390750]
event: FALLING EDGE offset: 13 timestamp: [1570281706.661435750]
event: RISING EDGE offset: 13 timestamp: [1570281706.661604000]
event: RISING EDGE offset: 13 timestamp: [1570281706.916220125]
event: FALLING EDGE offset: 13 timestamp: [1570281706.918247625]
Find gpio number
To use a GPIO line the gpio kernel number needs to be known. If we know the bank and the gpio line index, the kernel’s number can be calculated using the following formula on imx8 (arm64)
N = (BANK – 1) * 32 + IO
The kernel GPIO number for GPIO3_IO09 is
N = (3 – 1) * 32 + 9 = 73