I was playing with my Raspberry Pi over the weekend. I used a tutorial from Freenove that I followed to realize a few simple circuits that are controlled by the GPIO pins on the raspberry.
The Freenove tutorial is using a deprecated library named WiringPi. Besides the fact, that its deprecated, my understanding is that WiringPi adds additional abstractions and simplifications to allow users to focus on their circuits and less on writing boilerplate code to integrate low-level (C) libraries.
Now I want to gain a better understanding about how user space applications interface with the hardware GPIO pins and I am not worried about writing boilerplate code. So I started to play with libgpiod, which has a C API that can be used to read and set GPIO pins and that works well.
One thing that is not clear to me is how I can map the physical hardware GPIO pins on the 40pin connector (which are numbered from 1 to 40) to one of the 54 internal line numbers that gpiod reports when I use the gpioinfo
command.
On my Raspberry 3b+ with Raspbian 10 the gpioinfo
command prints the following, with all line names showing as unnamed
. The list goes on like this but I truncated it at 10 lines.
gpiochip0 - 54 lines:
line 0: unnamed unused output active-high
line 1: unnamed unused output active-high
line 2: unnamed unused output active-high
line 3: unnamed unused output active-high
line 4: unnamed unused output active-high
line 5: unnamed unused output active-high
line 6: unnamed unused output active-high
line 7: unnamed unused output active-high
line 8: unnamed unused output active-high
line 9: unnamed unused input active-high
line 10: unnamed unused input active-high
[...]
I found an issue about missing GPIO line names which discusses this problem but I do not understand the answer or why it was closed.
How am I supposed to lookup the line numbers of the chip based on a pin name such as GPIO17
? I found by trial and error that GPIO17
maps to line 17
, but for example CE0
maps to line 8
and SCL1
maps to line 3
, which I learned by trial and error using gpioset
.
I am not sure if its a good idea to hard-code this mapping into my application, or if I somehow should discover these values programmatically to make the program more portable?
I tried to use gpiod_ctxless_find_line
:
gpiod_ctxless_find_line ("SCL1", configuration->chipname, configuration->chipname_length, &offset);
but even while that returns a value of 0
(OK) the resulting offset is 66796
which is not the correct value. I assume it does not return anything, because gpioinfo
has no names for the lines.
If I write a C program using libgpiod
, can (should?) I discover these mappings at runtime, or is it ok to simply hard-code them? Is is possible that on a future Raspberry the SCL1
will not be at physical pin 5 or map to line 3?