🛠 Allumer une LED via le GPIO avec libgpiod
Objectives
Discover the 40-pin GPIO connector on the Raspberry Pi 4B (3.3 V logic, compatible with all previous Pi models) and light up an LED using libgpiod, the modern Linux kernel character interface that replaces the deprecated wiringPi. By the end, you will be able to control an output pin from a simple terminal.
Hardware
- Raspberry Pi 4B running Raspberry Pi OS Bookworm
- Red LED + 330 ohm resistor
- Breadboard and Dupont cables
- The BCM2711 SoC exposes up to 6 I2C, 6 UART, and 6 SPI interfaces; no embedded ADC.
Complete Code
sudo apt install gpiod
sudo adduser "$USER" gpio # puis reconnexion
# GPIO18 = broche physique 12 ; 330R en serie avec la LED, cathode vers GND
gpiodetect # doit afficher: gpiochip0 [brcmstb-gpio] (54 lines)
gpioinfo gpiochip0 | head -n 20
gpioset gpiochip0 18=1 # LED allumee
sleep 2
gpioset --duration=2s gpiochip0 18=0
for i in $(seq 1 10); do gpioset --duration=0.3s gpiochip0 18=1; sleep 0.3; done
Expected Verification
gpiodetect displays gpiochip0 (the BCM2711); the LED lights up for 2 seconds, then the loop makes it blink 10 times at approximately 2 Hz. No gpiochip device = gpio-mockup module or incomplete kernel.
Common Errors
- Confusing the physical pin number (pin 12) with the BCM number (GPIO18):
gpiosetexpects the BCM number. - Forgetting the resistor: the LED will burn out. For safety, never exceed 16 mA per pin or 50 mA total on the connector.
- Driving at 5 V instead of 3.3 V: GPIO logic is 3.3 V.
- Permission denied: you are not in the
gpiogroup (forgot to re-login) or you need to usesudo. - Later, for PWM, move to GPIO18 (pin 12): it is already the correct one here.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython