🛠 Premier script Python avec gpiozero
Objectives
Write and run a first Python script on the Raspberry Pi 5 using gpiozero, the default GPIO library for Raspberry Pi OS. gpiozero transparently handles the GPIO provided by the RP1 chip on the Pi 5. The script blinks an LED and reacts to a button.
Hardware
- Raspberry Pi 5 running 64-bit Raspberry Pi OS (gpiozero and Python 3 preinstalled)
- 1 LED + 470 Ω resistor on GPIO17 (physical pin 11)
- 1 push button on GPIO4 (physical pin 7) connected to GND
- Dupont wires and a breadboard
Complete code
#!/usr/bin/env python3
# blink.py — gpiozero est installé par défaut sur Raspberry Pi OS.
# Note Pi 5 : le GPIO est servi par la puce RP1 ; gpiozero le gère en interne.
from gpiozero import LED, Button # LED sur GPIO17, bouton sur GPIO4
from signal import pause
led = LED(17)
btn = Button(4, pull_up=True) # pull-up interne ; bouton broche vers GND
btn.when_pressed = led.blink # clignotement infini dès l'appui...
btn.when_released = led.close # ...et arrêt au relâchement
pause # maintient la boucle d'événements vivante
Expected behavior
Running python3 blink.py: nothing is displayed, and the LED remains off. Holding the button down makes the LED blink; releasing it turns the LED off. Ctrl-C terminates the script cleanly.
Common errors
- Forgetting
pause: the script terminates immediately and the LED never blinks. - Conflict with an older version of RPi.GPIO: on the Pi 5, prefer gpiozero or lgpio; old direct BCM2835 paths are broken.
- LED inserted backwards: the long leg (anode) goes to the GPIO, the short leg to the resistor and then to GND.
ModuleNotFoundError: gpiozero: install it withsudo apt install python3-gpiozero.- Running the script in a virtual environment without the system package: reinstall gpiozero in the venv using pip.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython