🛠 GPIO en C avec libgpiod : l'API caractère moderne
Goal
Drive the Zero's GPIO from C with the libgpiod character-device API — the maintained replacement for the deprecated sysfs and wiringPi approaches — and see what the BCM2835 exposes as a single GPIO chip.
Parts
- Zero with soldered 40-pin header ; LED + 330 Ohm from GPIO17 (physical pin 11) to GND
sudo apt install libgpiod-dev
Code
/* Build: gcc blink.c -o blink -lgpiod */
#include <gpiod.h>
#include <unistd.h>
int main(void) {
struct gpiod_chip *chip = gpiod_chip_open_by_name("gpiochip0");
if (!chip) return 1; /* the BCM2835 exposes one chip */
struct gpiod_line *led = gpiod_chip_get_line(chip, 17); /* GPIO17 */
gpiod_line_request_output(led, "blink", 0);
for (int i = 0; i < 10; i++) { /* 10 blinks, ~0.2 W each */
gpiod_line_set_value(led, i & 1);
usleep(250000);
}
gpiod_line_release(led);
gpiod_chip_close(chip);
return 0;
}
CLI tour: gpiodetect, gpioinfo gpiochip0, gpioset gpiochip0 17=1.
Check
The LED blinks 5 times at 2 Hz. While the program runs, gpioinfo gpiochip0 shows line 17 requested by 'blink' — and released on exit, so no 'pin stuck high' mysteries.
Bare-metal warning
Official docs state the BCM2835 peripheral specification 'contains a number of errors': cross-check the community errata list (elinux.org BCM2835 datasheet errata) before trusting any register description in driver or bare-metal work.
Pitfalls
- Mixing libgpiod and gpiozero on one line without releasing it: the second request fails with EBUSY.
- BCM numbering again: libgpiod line 17 = physical pin 11, not pin 17 (that is 3.3 V!).
- 16 mA per pin / 50 mA total still applies in C.
Autres tutoriels pour cette carte
- Premier démarrage de la Zero avec écran (mini-HDMI)
- Installation headless : la Zero en carte réseau USB (g_ether)
- Alimentation et consommation : le point faible de la Zero
- GPIO en Python : LED et bouton avec gpiozero
- Console série sur USB : la Zero en port série (CDC-ACM)
- Camera CSI sur Zero v1.3 : le nappe 22 broches
Exemples de code pour cette carte
clignotante.pyPythonbouton-gpio.pyPythoncapteur-i2c.shBashsurveillance-temperature.shBashcapteur-dht11.pyPythonservo-pwm-sysfs.shBash