🛠 Bouton poussoir et messages dans la console
Objectives
Read a logical state on a GPIO input and react in the console. You will wire a push button, enable the internal pull-up resistor to avoid an external component, then poll the pin in a loop to display a message on each press.
Hardware
- Raspberry Pi 2 Model B running 32-bit Raspberry Pi OS
- 1 push button
- Breadboard, 2 jumper wires
- Pins: GPIO4 (pin 7 on J8) and GND (pin 9)
- gpiod package installed (sudo apt install gpiod)
Complete code
#!/bin/bash
# bouton.sh — surveille GPIO4 (actif au niveau bas, pull-up interne)
CHIP=gpiochip0
while true; do
etat=$(sudo gpioget --pull-up $CHIP 4)
if [ "$etat" = "0" ]; then
echo "$(date +%T) : bouton appuye !"
while [ "$(sudo gpioget --pull-up $CHIP 4)" = "0" ]; do sleep 0.05; done
echo "$(date +%T) : bouton relache"
fi
sleep 0.05
done
Save as bouton.sh, then run: chmod +x bouton.sh && ./bouton.sh
Expected verification
Each press displays a timestamped line "button pressed!" followed by "button released" upon release. Without any press, the loop remains silent. Stop with Ctrl+C.
Common errors
- Forgetting the pull-up: without it, the pin floats and displays random states; the --pull-up option (or a resistor to 3.3 V) is essential.
- Wiring GPIO4 to 3.3 V instead of GND: you then need to invert the logic (active high).
- Confusing the physical pin number (7) with the GPIO number (4): always program using the GPIO number.
- Message spam: mechanical bounce of the button causes duplicates; the 50 ms delay after detection filters them out.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython