Traffic Light LEDs using Array
Introduction
In this LED example, we are creating a traffic light sequence, but instead of addressing every LED at every stage, we are going to put the GPIO pins in to an array, and address just the LEDs that need to change each time.
Here is a wiring diagram for the LED setup. This is what we will use when we run the software below.
We have wired the LEDs to GPIO pins 2, 6 & 10. These are the GPIO Pin numbers, not the actual Pi Pico Pin numbers.
Below is the software being used to drive the LEDs
- | download
#Traffic light LEDs using an array from machine import Pin import time # Define GPIO pins for the LEDs RED = Pin(2, Pin.OUT) AMBER = Pin(6, Pin.OUT) GREEN = Pin(10, Pin.OUT) # Put them in an array lights = [RED, AMBER, GREEN] # Helper function to turn all lights off def all_off(): for light in lights: light.off() while True: # Red all_off() RED.on() time.sleep(3) # Red + Amber AMBER.on() time.sleep(1) # Green all_off() GREEN.on() time.sleep(3) # Amber all_off() AMBER.on() time.sleep(1)
As you can see from the code, we have the four steps of the traffic light sequence. In step one, we can also turn off all the LEDs by calling the function we defined called all_off() with the command 'all_off()' command.
Here is the sequence running.

