Your First GPIO Script: Blinking an LED
Wire your first LED to the Pi and control it with Python — the RPi.GPIO library's version of the classic first blink.
You'll need: an LED, a resistor (330Ω is a safe default here), jumper wires, a breadboard, and your Pi.
Wire the LED and resistor exactly as in Lesson cb-02, but connect the resistor's free end to a GPIO pin instead of a battery — try physical pin 11 (GPIO17, per Lesson rpi-08's table) — and the LED's cathode to any GND pin.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
try:
while True:
GPIO.output(17, GPIO.HIGH)
time.sleep(1)
GPIO.output(17, GPIO.LOW)
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()GPIO.setmode(GPIO.BCM) tells the library you'll refer to pins by their BCM/GPIO number (17, matching physical pin 11) rather than physical position — picking one numbering scheme and sticking with it for the whole script avoids exactly the mix-up Lesson rpi-08 warned about. GPIO.setup(17, GPIO.OUT) configures that pin as an output, the same role as Arduino's pinMode(pin, OUTPUT). GPIO.output() then sets it HIGH or LOW, same as digitalWrite().
The try/except block matters here in a way it didn't on the Arduino: pressing Ctrl+C to stop a running Python script raises a KeyboardInterrupt, and without catching it, the script exits without releasing the GPIO pin cleanly — GPIO.cleanup() resets it. Run this with python3 blink.py from your terminal, and stop it any time with Ctrl+C.