🛠 Bouton poussoir et retour dans la console
Objectives
Read a digital input: a push button wired to GND with an internal pull-up, and display the state in the console on each press. You will learn about inverted logic (press = low level), mechanical bounce, and simple polling in the shell.
Hardware
- Raspberry Pi 3 Model B+ type board running Raspberry Pi OS
- 1 push button
- 2 Dupont wires (no external resistor needed: internal pull-up)
- Terminal access (SSH or keyboard/screen)
Complete Code
Wiring: pin 13 (GPIO27) → one leg of the button; other leg → pin 9 (GND). The internal pull-up keeps the line at 1 when idle.
#!/usr/bin/env bash
# bouton.sh — affiche un message à chaque appui (GPIO27, broche 13)
# Active le pull-up interne puis boucle sur la lecture de la ligne.
sudo gpioset --quiet --hold-period 0ms gpiochip0 27=0 2>/dev/null || true
echo "Appuyez sur le bouton (Ctrl-C pour quitter)..."
while true; do
# gpiodetect/gpiget : lecture de la ligne ; 0 = bouton pressé (logique inversée)
etat=$(sudo gpiget gpiochip0 27 2>/dev/null || echo 1)
if [ "$etat" = "0" ]; then
echo "Bouton pressé à $(date +%T)"
sleep 0.3 # anti-rebond logiciel grossier
while [ "$(sudo gpiget gpiochip0 27 2>/dev/null || echo 1)" = "0" ]; do
sleep 0.05 # attend le relâchement
done
fi
sleep 0.02
done
Expected Verification
Each press displays a line "Button pressed" with the time, only once per press despite mechanical bounce. When idle, the line reads 1 thanks to the internal pull-up; when pressed, it drops to 0.
Common Errors
- Forgetting the pull-up: the line floats, the state changes on its own (ghost counting).
- Getting the logic wrong: here pressed = 0, not 1; wiring the button to 3.3 V instead of GND inverts the logic.
- No debouncing: a single press triggers 5 to 20 detections.
- Confusing pin 13 (GPIO27) with GPIO13: check the mapping on the connector diagram.
- Using a PWM/I2C pin already claimed by an overlay: choose a free GPIO pin.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython