🛠 Premier script Python : faire clignoter la LED
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
- Raspberry Pi Model B Rev 1, Raspberry Pi OS legacy de 32 bits (Buster)
- LED + resistencia de 330 Ω en GPIO17 (pin 11) y GND (pin 6), como en el tutorial de LED
- Biblioteca:
sudo apt install -y python-rpi.gpio python3-rpi.gpio - Editor
nanoincluido en la imagen; Python está preinstalado.
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
RuntimeError: No access to /dev/mem: ejecutar consudoen las imágenes antiguas, o añadir el usuario al grupogpio.- Olvidar
GPIO.setmode(GPIO.BCM): RPi.GPIO rechaza entoncesGPIO.setup. - El script falla sin
finally: el pin permanece reclamado y el reinicio falla. ImportError: No module named RPi: paquete incorrecto (python vs python3) o biblioteca ausente.- En el ARM11 a 700 MHz, un
sleepmuy corto satura la CPU : mantener un mínimo de 0,1 s.
Otros tutoriales para esta placa
- 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
Ejemplos de código para esta placa
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython