🛠 Lire un bouton poussoir et afficher l'état dans la console
Objectives
Learn how to read a digital input on the 26-pin P1 connector of the Model B Rev 1: a push button connected to ground, with the internal pull-up resistor of the BCM2835 enabled via libgpiod. You will monitor the button state in a loop in the console.
Hardware
- Raspberry Pi Model B Rev 1 running Raspberry Pi OS legacy 32-bit
- 1 push button
- libgpiod installed (
sudo apt install -y gpiod) - No external resistor required: the internal pull-up is sufficient for a button connected to GND.
Complete code
#!/bin/sh
# bouton.sh - surveille un bouton sur GPIO4 (broche physique 7)
# c'est la broche 7, GND est la broche 9.
# Rappel interne : GPIO4 possède un pull-up interne activable.
# Lecture en boucle : gpiomon attend les changements d'état
gpiomon --num-events=0 --rising-edge gpiochip0 4 &
while true; do
ETAT=$(gpioget --bypass-direction-check gpiochip0 4 2>/dev/null || gpioget gpiochip0 4)
if [ "$ETAT" = "0" ]; then
echo "BOUTON APPUYE (etat bas = 0, pull-up interne)"
else
echo "au repos (1)"
fi
sleep 0.1
done
Expected verification
At rest, the console displays au repos (1) thanks to the internal pull-up. Each time the button is pressed, the GPIO is connected to ground and the state changes to 0: the console displays BOUTON APPUYE. The button is wired between pin 7 (GPIO4) and pin 9 (GND).
Common errors
- Forgetting the pull-up: without a pull-up (internal or external), the input floats and displays random states.
- Wiring the button between GPIO and 3.3 V without a resistor: short circuit when pressed if the low state is read with a pull-down.
- Using the wrong pin: GPIO4 is physical pin 7 on the 26-pin connector, not pin 4.
- Mechanical bouncing: the state may oscillate for a few milliseconds; the
sleep 0.1is a minimalist software debounce. gpiomondoes not exist on very old images: update thegpiodpackage.
Other tutorials for this board
- Allumer une LED via le GPIO avec libgpiod
- Premier script Python : faire clignoter la LED
- Variation d'intensité LED avec le PWM matériel (et son piège)
- Lire un capteur I2C (température/humidité) sur le bus 1
- Configurer l'Ethernet 10/100 et piloter le Pi en SSH
- Boot sur SD, partitions et procédure de recouvrement
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython