🛠 Premier script Python sur Raspbian legacy
Objectives
Write, make executable, and run a first complete Python script on the Model B Rev 2: text display, loop, and LED control using RPi.GPIO, the standard library from the Raspbian era.
Hardware
- Raspberry Pi Model B Rev 2 (512 MB), HDMI screen or SSH session, keyboard
- LED + 330 Ω resistor on GPIO17 (P1-11) to GND
sudo apt install python-rpi.gpio(Raspbian legacy 32-bit, python2; ARMv6 is no longer supported by recent images)
Complete code
#!/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.")
Expected verification
nano hello_led.py
chmod +x hello_led.py
sudo ./hello_led.py
The terminal displays the message followed by the ten iterations; the LED blinks for one second per cycle; the script stops on its own and turns off the LED.
Common errors
- Forgetting
chmod +xor the shebang#!/usr/bin/env python: "command not found" when launching directly. - Mixed indentation (spaces/tabs): Python 2 is permissive, Python 3 is not.
- Running without sudo on an image where the gpio group is not configured.
- Missing
GPIO.cleanup: the pin remains claimed and the second run fails.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython