🛠 Premier script Python sur le Pi
Objectives
Write, make executable, and run a first Python 3 script on the Raspberry Pi 3 Model B. Understand the shebang (#!/usr/bin/env python3), execution permissions (chmod +x), and control the LED from the previous tutorial using Python with gpiozero (preinstalled on Raspberry Pi OS). This is the foundation for all the automations we will run as systemd services later.
Hardware
- Raspberry Pi 3 Model B running Raspberry Pi OS Lite (Python 3 included)
- LED + 330 Ω resistor on GPIO17 (physical pin 11), as in tutorial 1
nanoeditor (included) and SSH terminal- No libraries to install:
gpiozerois preinstalled
Complete Code
#!/usr/bin/env python3
"""clignot.py — premier script : message console + LED sur GPIO17.
gpiozero est préinstallé sur Raspberry Pi OS (Pi 3B inclus)."""
from gpiozero import LED
from time import sleep
led = LED(17) # BCM17 = broche physique 11 (logique 3,3 V)
print("Bonjour depuis le Raspberry Pi 3 Model B !")
for i in range(5):
led.on
print(f"Cycle {i + 1} : LED allumée")
sleep(0.2)
led.off
sleep(0.3)
print("Terminé.")
Save as clignot.py, then:
chmod +x clignot.py # droit d'exécution
./clignot.py # lancer depuis le dossier courant
Expected Verification
The terminal displays "Hello from the Raspberry Pi 3 Model B!" followed by the 5 cycle lines, while the LED blinks (200 ms on, 300 ms off). The script terminates cleanly with "Done.". Rerunning with python3 clignot.py must yield exactly the same result — the shebang is just a shortcut.
Common Errors
Permission deniedwhen running./clignot.py: forgettingchmod +x— or the file was created on an SD card mounted as FAT from Windows.bad interpreter: file written with Windows line endings (CRLF); fix withdos2unix clignot.py.ModuleNotFoundError: gpiozero: on a third-party distribution (Ubuntu, Alpine), installpython3-gpiozeroor runpip install gpiozero.RuntimeError: No suitable pin factory: running as root without a graphical environment; on Raspberry Pi OS Lite, keepgpiozerodefaults and avoid unnecessarysudo.- Mixed Python indentation (spaces/tabs):
nanomay paste tabs, prefer 4 spaces. - Forgetting that GPIO17 is 3.3 V: never connect a 5 V input to the pin.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython