TLDR; doubts:
- When using CLI, what is the easiest way to manage GPIOs on the Pi? What is the more correct (official) way?
- Is there some official documentation about this topic for the Pi and Raspberry Pi OS? (I wasn't able to find it)
- What are gpiochip512, gpiochip570, gpiochip578 that I see when doing
ls /sys/class/gpio/? - Are there other ways other than
/sys/class/gpio/exportandpinctrlto control GPIOs? - What are the benefits from using one method over the other?
Context
I have a Raspberry Pi 4 with Raspberry Pi OS (Bookworm). I was using Raspbian until last week when I upgraded to the latest Raspberry Pi OS (I delayed that because I didn't have a real need to upgrade and updating always takes some time).
Well now I see that the method I was using to access gpio pins and using them changed.
Example
The example below just turns on a LED attached to GPIO 13.
Method 1 - /sys/class/gpio/export
I was using:
echo 13 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio13/direction
echo 1 > /sys/class/gpio/gpio13/value
But that now throws an error:
$ echo 13 > /sys/class/gpio/export
-bash: echo: write error: Invalid argument
So I did some online searching and found these two resources:
- An answer to "Trying to write to /sys/class/gpio/export – write error: Invalid argument - Super User"
- Accessing GPIO pins from a BASH script on a Raspberry Pi 5 - Raspberry Pi Forums.
The first one states that the GPIO pin numbers have changed somehow and I was able to use this to replaces my previous code to:
echo 525 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio525/direction
echo 1 > /sys/class/gpio/gpio525/value
To come up with that 525 this was my logic:
$ ls /sys/class/gpio/
export gpiochip512 gpiochip570 gpiochip578 unexport
$ cat /sys/class/gpio/gpiochip5*/ngpio
58
8
2
So I guessed that the one starting with 512 was the one I could use, it's the only one that has 40 or more pins. And then I just added 13 to that starting point.
Method 2 - pinctrl
I also tried pinctrl from the second link, which translates my example to:
pinctrl set 13 op
pinctrl set 13 dh