🛠 Bouton poussoir et retour sur la console
Objectives
- Read a logical state (0/1) on a GPIO pin using a push button.
- Use the internal pull-up resistor instead of an external resistor.
- Display the button state on the console — useful on the Model A, where the only console may be the UART on the GPIO pins.
Hardware
- Raspberry Pi Model A running Raspberry Pi OS legacy 32-bit.
- 1 push button (no external resistor required).
- USB-TTL serial console on GPIO14/15 (enable_uart=1 in config.txt) or a USB keyboard via a hub.
Complete code
# Lecture événementielle avec gpiomon (libgpiod)
sudo gpiomon --rising-edge --num-events=0 gpiochip0 4
# Version Python avec la bibliothèque héritée RPi.GPIO
python3 - <<'PY'
import RPi.GPIO as GPIO, time
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
while True:
print("bouton:", "APPUYE" if not GPIO.input(4) else "libre", flush=True)
time.sleep(0.05)
finally:
GPIO.cleanup
PY
Expected verification
Each press displays a rise event (gpiomon) or “button: PRESSED” then “released” upon interruption. The circuit is active-low: at rest, the input is pulled to 3.3 V by the internal pull-up.
Common errors
- Forgetting
pull_up_down=GPIO.PUD_UP: the input floats and displays random states. - Choosing the wrong pin: physical pin 7 = GPIO4, not GPIO7.
- Connecting the button between GPIO and 3.3 V assuming a pull-down: it does not exist by default.
- Running
gpiomonwithoutsudoon legacy images: permission denied on /dev/gpiochip0.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython