🛠 Premier script Python : faire clignoter la LED

Raspberry Pi Model B (Rev 1, 2012) — Fiche carte · debutant · Schéma : IMG-model-b-rev1-debutant-3-modelb1-premier-script-python.svg — Script Python exécuté dans le terminal, LED sur GPIO17 clignotant, éditeur de texte montrant le code du programme

Objectifs

Écrire et exécuter votre premier script Python sur le Raspberry Pi Model B Rev 1 (Python 2 ou 3 selon l'image legacy). Le script fait clignoter une LED sur GPIO17 avec la bibliothèque RPi.GPIO, la référence historique sur BCM2835. Compétences visées : créer un fichier, l'éditer avec nano, le lancer, l'interrompre avec Ctrl-C.

Matériel

Code complet

#!/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

Vérification attendue

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

La LED clignote à 1 Hz. Sur les images Buster où python3 n'est pas le défaut, essayez python clignote.py (Python 2, adapter l'import).

Erreurs fréquentes

Autres tutoriels pour cette carte

Exemples de code pour cette carte

← Retour à la fiche 🛠 Tous les tutoriels