🛠 Allumer une LED en C avec libgpiod sur le GPIO 40 broches
Objectives
Turn on an LED in C using libgpiod on GPIO17 of the 40-pin connector on the Raspberry Pi 3 Model A+ (Broadcom BCM2837B0 SoC). Understand the difference between physical pin and Broadcom number, and manipulate gpiochip0.
Hardware
- Raspberry Pi 3 A+ powered by 5 V / 2.5 A (micro-USB), Raspberry Pi OS Lite Bookworm
- LED + 330 Ω resistor, female-male Dupont cables
- 40-pin pinout: GPIO17 = pin 11, GND = pin 14; 3.3 V logic only, no onboard ADC/DAC
Complete code
/* blink.c — Build: gcc blink.c -o blink -lgpiod (paquet libgpiod1-dev) */
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
/* gpiochip0 = banque des GPIO du SoC sur le connecteur 40 broches */
struct gpiod_chip *chip = gpiod_chip_open_by_name("gpiochip0");
if (!chip) { perror("gpiochip0"); return 1; }
struct gpiod_line *line = gpiod_chip_get_line(chip, 17); /* GPIO17 */
if (gpiod_line_request_output(line, "blink", 0) < 0) { perror("request"); return 1; }
for (int i = 0; i < 10; i++) {
gpiod_line_set_value(line, 1); /* LED on */
usleep(200000);
gpiod_line_set_value(line, 0); /* LED off */
usleep(200000);
}
gpiod_line_release(line);
gpiod_chip_close(chip);
return 0;
}
sudo apt install -y libgpiod1-dev gcc
gcc blink.c -o blink -lgpiod && ./blink
# Sans compiler : sudo gpiodetect && sudo gpioset gpiochip0 17=1
Expected verification
gpiodetect displays gpiochip0; the LED blinks 10 times (200 ms ON / 200 ms OFF). Quick test without compiling: sudo gpioset gpiochip0 17=1 then 17=0.
Common errors
- Confusing physical pin 11 and GPIO17: always reason in Broadcom numbering.
- Forgetting the 330 Ω resistor or powering the LED from 5 V instead of 3.3 V.
- Debian 13/Trixie has moved to libgpiod v2 (
gpiod_ctx_*API): the code targets v1.6 of Bookworm. - Permission denied: run with sudo or add the user to the
gpiogroup.
Other tutorials for this board
- Bouton poussoir et retour console avec gpiozero
- Premier script Python : inventaire du système
- Variation d'intensité d'une LED avec le PWM matériel
- Capteur I2C : température et pression avec BME280
- Connexion WiFi station et administration en SSH
- Démarrage SD/USB et récupération d'une carte qui ne boot plus
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython