🛠 Premier script Python : faire clignoter la LED

Raspberry Pi Model B (Rev 1, 2012) — Board Sheet · debutant · Schéma : IMG-model-b-rev1-debutant-3-modelb1-premier-script-python.svg — Script Python exécuté dans le terminal, LED sur GPIO17 clignotant, éditeur de texte montrant le code du programme

Objectives

Write and run your first Python script on the Raspberry Pi Model B Rev 1 (Python 2 or 3 depending on the legacy image). The script blinks an LED on GPIO17 using the RPi.GPIO library, the historical reference on BCM2835. Skills covered: creating a file, editing it with nano, running it, and interrupting it with Ctrl-C.

Hardware

Complete code

#!/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

Expected verification

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

The LED blinks at 1 Hz. On Buster images where python3 is not the default, try python clignote.py (Python 2, adapt the import).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials