🛠 Premier script Python : faire clignoter la LED
Objectives
Write and run your first Python 3 script on the Raspberry Pi 2: a loop that blinks an LED, with a counter and clean shutdown. You will learn how to create a file, make it executable, handle Ctrl+C, and use the gpiozero library, the simplest one for beginners.
Hardware
- Raspberry Pi 2 Model B running 32-bit Raspberry Pi OS
- LED + 330 Ω resistor on GPIO17 (as in the LED tutorial)
- Package: sudo apt install python3-gpiozero
Complete code
#!/usr/bin/env python3
"""blink.py — fait clignoter une LED sur GPIO17 avec gpiozero."""
from gpiozero import LED
from time import sleep
led = LED(17) # broche BCM17 du connecteur J8
def on:
print("LED allumee")
def off:
print("LED eteinte")
led.when_on = on
led.when_off = off
try:
for i in range(10):
print(f"Cycle {i + 1}/10")
led.on
sleep(0.5)
led.off
sleep(0.5)
print("Termine")
except KeyboardInterrupt:
led.close
print("Arrete proprement")
Expected verification
The LED blinks once per second (0.5 s on, 0.5 s off) for 10 cycles, and the terminal displays each cycle. Ctrl+C displays "Stopped cleanly" and turns off the LED. Since the Pi 2 is quad-core (4× Cortex-A7 at 900 MHz), the script remains very lightweight: a single core is more than sufficient.
Common errors
- gpiozero module not found: install python3-gpiozero, not the old Python 2 package.
- Permission denied on the GPIO: on recent kernels, add your user to the gpio group or run with sudo.
- Incorrect pin number: gpiozero uses BCM numbering; physical pin 11 corresponds to GPIO17.
- The LED stays on after Ctrl+C: you must call led.close to release the pin.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython