🛠 Premier script Python : faire clignoter la LED
Objectives
Write and run your first Python script on the Raspberry Pi Model B Rev 1 (Python 2 or 3 depending on the legacy image). The script blinks an LED on GPIO17 using the RPi.GPIO library, the historical reference on BCM2835. Skills covered: creating a file, editing it with nano, running it, and interrupting it with Ctrl-C.
Hardware
- Raspberry Pi Model B Rev 1, Raspberry Pi OS legacy 32-bit (Buster)
- LED + 330 Ω resistor on GPIO17 (pin 11) and GND (pin 6), as in the LED tutorial
- Library:
sudo apt install -y python-rpi.gpio python3-rpi.gpio nanoeditor provided with the image; Python is preinstalled.
Complete code
#!/usr/bin/env python3
"""Clignotement LED sur GPIO17 - Raspberry Pi Model B Rev 1 (BCM2835)."""
import RPi.GPIO as GPIO # sudo apt install python3-rpi.gpio
import time
LED = 17 # numerotation BCM : GPIO17 = broche physique 11
GPIO.setmode(GPIO.BCM) # numeros Broadcom, pas positions physiques
GPIO.setup(LED, GPIO.OUT)
try:
while True:
GPIO.output(LED, GPIO.HIGH) # LED allumee
time.sleep(0.5)
GPIO.output(LED, GPIO.LOW) # LED eteinte
time.sleep(0.5)
except KeyboardInterrupt:
pass # Ctrl-C arrete proprement
finally:
GPIO.cleanup # toujours liberer la broche
Expected verification
nano clignote.py # coller le code, Ctrl-O puis Ctrl-X
python3 clignote.py # la LED clignote 2 fois par seconde
# Ctrl-C : le script s'arrete, GPIO.cleanup libere la broche
The LED blinks at 1 Hz. On Buster images where python3 is not the default, try python clignote.py (Python 2, adapt the import).
Common errors
RuntimeError: No access to /dev/mem: run withsudoon older images, or add the user to thegpiogroup.- Forgetting
GPIO.setmode(GPIO.BCM): RPi.GPIO then refusesGPIO.setup. - The script crashes without
finally: the pin remains claimed and restarting fails. ImportError: No module named RPi: wrong package (python vs python3) or missing library.- On the 700 MHz ARM11, a very short
sleepsaturates the CPU: stay at 0.1 s minimum.
Other tutorials for this board
- Allumer une LED via le GPIO avec libgpiod
- Lire un bouton poussoir et afficher l'état dans la console
- Variation d'intensité LED avec le PWM matériel (et son piège)
- Lire un capteur I2C (température/humidité) sur le bus 1
- Configurer l'Ethernet 10/100 et piloter le Pi en SSH
- Boot sur SD, partitions et procédure de recouvrement
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython