🛠 Premier script Python : faire clignoter la LED

Raspberry Pi 2 Model B (2015) — Board Sheet · debutant · Schéma : IMG-model-2b-debutant-1-model2b-premier-python.svg — script Python exécuté dans le terminal, LED clignotante reliée au GPIO17, éditeur de texte ouvert sur blink.py

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials