🛠 Lire un bouton et afficher dans la console
Objectives
Wire a push button to the Raspberry Pi 5 and display a message in the console on each press, using gpiomon (libgpiod) and then a small Shell script. This introduces GPIO inputs, internal pull-up resistors, and edge detection.
Hardware
- Raspberry Pi 5 running Raspberry Pi OS 64-bit
- 1 push button
- Dupont cables
- Pinout: physical pin 7 = GPIO4 (input), physical pin 6 = GND. No external components are needed thanks to the internal pull-up resistor.
Complete code
# Écouter les fronts sur GPIO4 (libgpiod v2)
sudo apt install -y gpiod
gpiomon --num-events=0 --rising-edge gpiochip0 4
# Script bouton.sh : journaliser chaque appui
cat > bouton.sh <<'EOF'
#!/usr/bin/env bash
# Bouton sur GPIO4 (broche physique 7), pull-up interne : appui = niveau 0
echo "Surveillance de GPIO4... Ctrl-C pour terminer"
gpiomon --num-events=0 --falling-edge --debounce-period 0.05 gpiochip0 4 | while read -r _; do
echo "$(date '+%H:%M:%S') - bouton pressé !"
done
EOF
chmod +x bouton.sh
./bouton.sh
Expected verification
Each press of the button displays a timestamped line "button pressed!" in the terminal. With gpiomon --rising-edge, it is the release that triggers the event.
Common errors
- Button wired to 3.3 V without a resistor: short circuit when pressed if the pin is configured as an output. Here we wire to GND with a pull-up, which is safe.
- Mechanical bouncing: multiple events for a single press; the
--debounce-period 0.05option in gpiomon filters these out. - Wrong pin: GPIO4 = physical pin 7. Verify with the
pinoutcommand (provided with gpiozero) orgpioinfo gpiochip0. - Running without sufficient privileges: on some configurations, accessing the GPIO requires being in the
gpiogroup or using sudo. - Confusing libgpiod versions: the syntax
gpiomon gpiochip0 4corresponds to v2 (Bookworm).
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython