🛠 Premier script Python sur Raspbian legacy
Objectifs
Écrire, rendre exécutable et lancer un premier script Python complet sur le Model B Rev 2 : affichage texte, boucle, et pilotage d'une LED avec RPi.GPIO, la bibliothèque standard de l'ère Raspbian.
Matériel
- Raspberry Pi Model B Rev 2 (512 MB), écran HDMI ou session SSH, clavier
- LED + résistance 330 Ω sur GPIO17 (P1-11) vers GND
sudo apt install python-rpi.gpio(Raspbian legacy 32 bits, python2 ; l'ARMv6 n'est plus supporte par les images recentes)
Code complet
#!/usr/bin/env python
# hello_led.py - premier script: bonjour + LED qui clignote sur GPIO17
import RPi.GPIO as GPIO
import time
LED = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
print("Bonjour depuis le Raspberry Pi Model B Rev 2 (BCM2835, 512 MB)")
try:
for i in range(10):
GPIO.output(LED, GPIO.HIGH)
print("iteration %d" % (i + 1))
time.sleep(0.5)
GPIO.output(LED, GPIO.LOW)
time.sleep(0.5)
finally:
GPIO.cleanup
print("Termine.")
Vérification attendue
nano hello_led.py
chmod +x hello_led.py
sudo ./hello_led.py
Le terminal affiche le message puis les dix itérations ; la LED clignote une seconde par cycle ; le script s'arrête seul et éteint la LED.
Erreurs fréquentes
- Oublier
chmod +xou le shebang#!/usr/bin/env python: « commande introuvable » au lancement direct. - Indentation mélangée espaces/tabulations : Python 2 est permissif, Python 3 non.
- Lancer sans sudo sur une image où le groupe gpio n'est pas configuré.
GPIO.cleanupabsent : la broche reste revendue et le second lancement échoue.
Autres tutoriels pour cette carte
Exemples de code pour cette carte
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython