🛠 Premier script Python sur le Pi

Raspberry Pi 3 Model B (model-3b) · debutant · Schéma : IMG-model-3b-debutant-3-model3b-premier-script-python.svg — flux d'un script Python : éditeur nano, shebang, chmod +x, exécution dans le terminal et sortie LED GPIO17

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials