🛠 Lire un bouton et afficher dans la console
Objectives
Read the state of a push button on the Raspberry Pi 3 Model B GPIO and display a message in the console on each press. Learn how to enable the internal pull-up resistor (the button is wired to GND, active-low logic) and how to avoid mechanical bouncing with a software delay.
Hardware
- Raspberry Pi 3 Model B running Raspberry Pi OS Lite
- 1 push button (tactile switch)
- Breadboard, Dupont wires
- SSH terminal or screen + keyboard on the Pi
libgpiod-utilspackage installed (sudo apt install -y libgpiod-utils)
Complete code
The button is wired between physical pin 7 (GPIO4) and physical pin 6 (GND). The internal pull-up keeps the input at 1 when idle; pressing the button brings it to 0:
#!/usr/bin/env bash
# bouton.sh — surveille GPIO4 (broche physique 7), bouton vers GND
# requis : libgpiod-utils (gpiodetect, gpioget)
echo "Surveillance GPIO4 — Ctrl-C pour quitter"
while true; do
etat=$(gpioget --numeric gpiochip0 4)
if [ "$etat" = 0 ]; then
echo "$(date +%T) : bouton appuyé !"
sleep 0.3 # anti-rebond logiciel
fi
sleep 0.05
done
Save as bouton.sh, then run chmod +x bouton.sh and ./bouton.sh. Python alternative: from gpiozero import Button; b = Button(4, pull_up=True) then b.wait_for_press — gpiozero is preinstalled on Raspberry Pi OS.
Expected verification
When idle, gpioget gpiochip0 4 returns 1 (internal pull-up). On each button press held down, the console displays a timestamped line "button pressed!". Upon release, the state returns to 1. Without the pull-up enabled, the input floats and displays random states — this is the best test to understand their usefulness.
Common errors
- Forgetting the pull-up (or wiring an external 10 kΩ one at the same time): the input floats, causing spurious messages.
- Wiring the button to 3.3 V without a resistor and then reading: short circuit to GND when pressed if the pin is set as high output.
- Wrong pin: GPIO4 = physical pin 7, not pin 4 (which is 5 V).
- Mechanical bouncing: without a delay, a single press may produce multiple lines — normal, hence the
sleep 0.3. permission deniedon gpiochip0: add the user to thegpiogroup and log out/in again.- Using
gpiogetin a very tight loop on an old Pi: consumes CPU; keep a shortsleep.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython