🛠 Lire un bouton poussoir en Python avec python3-libgpiod
Objectives
Wire a push button to the 40-pin connector of the ROCK 3B and display each press in the console using python3-libgpiod, utilizing interrupt events (rising edge) rather than polling in a loop. This is the first Python script in the series: it serves as a foundation for sensor and IoT tutorials.
Hardware
- Radxa ROCK 3B running Radxa OS, USB-C PD 12 V / 2 A power supply
- 1 push button, 1 10 kΩ resistor (pull-up to 3.3 V), Dupont cables
sudo apt install python3-gpiod gpiod
Complete Code
#!/usr/bin/env python3
"""Bouton sur le connecteur 40 broches — affiche les appuis (ROCK 3B).
Résolvez CHIP/LINE avec `gpiofind PIN_11` sur VOTRE image : les numéros
diffèrent entre noyau constructeur (Radxa) et noyau mainline >= 6.11."""
from gpiod import Chip, LineRequest
CHIP, LINE = "gpiochip3", 1 # exemple GPIO3_A1 derrière PIN_11 — CONFIRMER
with Chip(CHIP) as chip:
req = chip.request_lines(
consumer="rock3b-demo",
config={LINE: LineRequest.REQUEST_INPUT},
)
print("appui attendu (front montant), Ctrl-C pour quitter")
while True:
for ev in req.event_wait(timeout_ms=None):
e = req.event_get
if e and e.event_type == 1 and e.line == LINE: # RISING_EDGE
print("bouton pressé")
Expected Verification
sudo python3 bouton.py starts without errors; each press (rising edge) displays "button pressed". Ctrl-C releases the line cleanly. With a hardware pull-up + button to ground, the idle state is 1 and the pressed state is 0: if nothing is displayed, swap the button/cable or test sudo gpioget $(gpiofind PIN_11) with a logic multimeter.
Common Errors
- Copying CHIP/LINE numbers from another tutorial: Radxa's GPIOD documentation insists — always resolve with
gpiofind PIN_xx, as the mapping changes between the manufacturer image and mainline. - python3-libgpiod API: recent versions (libgpiod v2) use
request_lines(config=...), older ones useline.request(consumer=..., type=...)— adapt according to the installed Debian package. - Leaving the pin floating without a pull: the state oscillates randomly; a 10 kΩ hardware pull-up to 3.3 V is the most educational approach.
- Confusing the physical connector pin with the libgpiod line: only the line number matters to the script.
- Forgetting the common ground between the breadboard and the board: the rising edge never arrives cleanly.
Other tutorials for this board
- Faire clignoter une LED via le GPIO avec libgpiod
- Premier réseau : Ethernet double gigabit, Wi-Fi optionnel et SSH
- Installer et booter le système sur un SSD NVMe (M.2 M-Key)
- Interroger un capteur I2C sur le connecteur 40 broches
- Surveiller température et fréquence CPU, piloter le ventilateur PWM
- Routeur / passerelle réseau double Gigabit avec OpenWrt et PoE
Code examples for this board
clignotante.pyPythonbouton-gpio.pyPythoncapteur-i2c.shBashsurveillance-temperature.shBashcapteur-dht11.pyPythonservo-pwm-sysfs.shBash