GPIO Basics: Blinking an LED
Blinking an LED is the classic first physical-computing project, and it's the perfect way to prove your Zero W's GPIO header, your wiring, and your code all work together before moving on to anything more complex.
What You'll Need
| Item | Why |
|---|---|
| An LED | The thing you're actually lighting up |
| A current-limiting resistor (330 ohm is a safe, common value) | Without it, an LED will draw too much current from the GPIO pin, which can damage the LED and potentially the pin driving it - the resistor limits current to a safe level |
| A breadboard | Makes wiring temporary connections easy without soldering |
| Jumper wires | To connect the breadboard to the GPIO header |
Wiring It Up
LEDs have two legs of different lengths: the longer leg is the anode (positive) and the shorter leg is the cathode (negative). Wire the circuit like this:
- The LED's longer leg (anode) connects through the resistor to physical pin 11, which is GPIO17 in code.
- The LED's shorter leg (cathode) connects to a ground pin - physical pin 9 is a convenient one nearby.
The resistor can sit on either side of the LED in the circuit (between the pin and the anode, or between the cathode and ground) - what matters is that it's somewhere in that single loop limiting the current.
The Code
For a first GPIO project like this, the currently-recommended library is gpiozero - it ships
with Raspberry Pi OS and has a simple, readable, high-level API. The older, lower-level
RPi.GPIO library still exists and still works, and you'll see it in plenty of older
tutorials, but it requires more manual setup code (configuring pin modes, cleanup, etc.) for the
same result - gpiozero is simpler and is the one to actually use for this.
from gpiozero import LED
from time import sleep
led = LED(17)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
.py file on your Zero W (over the SSH connection from the previous lesson) and run it with python3 blink.py.How the Code Works
from gpiozero import LED- imports theLEDclass, which wraps up the details of driving a GPIO pin high and low.from time import sleep- imports Python's built-insleepfunction so we can pause between blinks.led = LED(17)- creates an LED object attached to GPIO17 (the BCM number, corresponding to physical pin 11, exactly as wired above).led.on()andled.off()- set that GPIO pin high (3.3V) or low (0V), turning the LED on or off.sleep(1)- pauses execution for 1 second so you can actually see each state.- The
while True:loop repeats the on/off/sleep sequence forever, producing a steady blink. (You could also replace the loop body withled.blink(), which does the same on/off/sleep cycle for you.)