🛠 Premier script Python : faire clignoter la LED
Objectives
Issue commands to programs: write, run, and cleanly stop a first Python 3 script that blinks the LED from tutorial 1, using the RPi.GPIO library still provided on legacy images (ARMv6).
Hardware
- Raspberry Pi Model B+ running 32-bit Raspberry Pi OS legacy
- LED + 330 Ω resistor wired to GPIO17 (pin 11) and GND (pin 14), as in tutorial 1
- Keyboard/HDMI screen or SSH session over the B+'s Ethernet
Complete code
# Installation de la bibliothèque GPIO pour Python 3
sudo apt update && sudo apt install -y python3-rpi.gpio
nano blink.py # coller le script ci-dessous, puis Ctrl+O, Ctrl+X
sudo python3 blink.py
#!/usr/bin/env python3
"""Clignotant LED sur GPIO17 (broche 11) — Raspberry Pi Model B+."""
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # on raisonne en numérotation BCM
GPIO.setup(17, GPIO.OUT)
try:
for _ in range(10): # 10 clignotements
GPIO.output(17, GPIO.HIGH)
time.sleep(0.3)
GPIO.output(17, GPIO.LOW)
time.sleep(0.3)
finally:
GPIO.cleanup # rend la broche propre à la sortie
Expected verification
The LED blinks 10 times (0.3 s on / 0.3 s off) then the script terminates without any message. Ctrl+C interrupts the program and still triggers GPIO.cleanup thanks to the finally block.
Common errors
- Forgetting sudo: RPi.GPIO raises an exception "No access to /dev/gpiomem".
- Missing setmode or confusing BCM/BOARD: "Please set pin numbering mode" or silent LED.
- Using python (Python 2) instead of python3 on a recent image: module not found.
- Script launched twice: the pin is already in use, close the other terminal.
Other tutorials for this board
- Allumer une LED depuis la GPIO 17 avec libgpiod
- Lire un bouton et afficher les appuis dans la console
- Variation d'intensité d'une LED avec le PWM matériel (GPIO18)
- Interroger un capteur I2C (BME280) sur le bus du 40 broches
- Mettre le B+ en réseau par Ethernet et piloter en SSH
- Amorçage microSD, pannes de boot et procédure de recouvrement
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython