LED Patterns with Loops and Arrays
The big idea: once you can control one LED with your Raspberry Pi Pico, controlling six is not six times harder — it is almost the same amount of code. The trick is to stop copying and pasting one command per LED, and instead put all your LEDs into a single list (also called an array) and then walk through that list with a for loop.
In this lesson you will turn a row of little lights into animations: lights that chase each other, bounce back and forth, count in binary, sparkle randomly, and even act as a real traffic light. Every one of these effects is just a list of LEDs plus a clever loop. Master this and you have unlocked the core skill behind almost every light show, scoreboard, and status display ever built.
What you will be able to do
- Wire 4 to 6 LEDs, each on its own GPIO pin, each with its own resistor.
- Store many
Pinobjects in one Python list and understand what a list actually is. - Use a
forloop to turn all LEDs on or off with just two or three lines. - Build a running light (the famous "Knight Rider" chase) and a bounce effect.
- Show numbers in binary on your LEDs, and understand what binary means.
- Make a random sparkle using the
randommodule. - Wrap each pattern in a function so you can reuse it by name.
- Change the animation speed from a single variable.
- Understand why
time.ticks_ms()can be better thansleep()(non-blocking timing). - Build a working traffic light and fix the two most common wiring/order bugs.
1. Wiring 4 to 6 LEDs
An LED (Light-Emitting Diode) is a tiny light that only lets electricity flow one way. It has two legs:
- The long leg is the anode (the plus,
+side). This connects toward the GPIO pin.