🛠 Premier script Python avec gpiozero

Raspberry Pi 5 (model-5) · debutant · Schéma : IMG-model-5-debutant-3-model5-d3-premier-script-python.svg — Raspberry Pi 5 avec LED sur GPIO17 et bouton sur GPIO4 pilotés par un script Python gpiozero dans un terminal

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials