🛠 Premier script Python : faire clignoter la LED

Raspberry Pi Model B (Rev 1, 2012) — Ficha de placa · 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

Objetivos

Escribir y ejecutar su primer script de Python en la Raspberry Pi Model B Rev 1 (Python 2 o 3 según la imagen legacy). El script hace parpadear un LED en GPIO17 con la biblioteca RPi.GPIO, la referencia histórica sobre BCM2835. Competencias previstas: crear un archivo, editarlo con nano, ejecutarlo e interrumpirlo con Ctrl-C.

Material

Código completo

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

Verificación esperada

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

El LED parpadea a 1 Hz. En las imágenes de Buster donde python3 no es el valor predeterminado, pruebe python clignote.py (Python 2, adapte la importación).

Errores frecuentes

Otros tutoriales para esta placa

Ejemplos de código para esta placa

← Volver a la ficha 🛠 Todos los tutoriales