import time
import RPi.GPIO as GPIO
# Set up GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
led_pins = {"red": 17, "green": 27, "blue": 22}
for pin in led_pins.values():
GPIO.setup(pin, GPIO.OUT)
def traffic_light():
# Switch on red light
GPIO.output(led_pins["red"], GPIO.HIGH)
GPIO.output(led_pins["green"], GPIO.LOW)
GPIO.output(led_pins["blue"], GPIO.LOW)
time.sleep(5) # Run the red light for 5 seconds
# Switch on green light
GPIO.output(led_pins["red"], GPIO.LOW)
GPIO.output(led_pins["green"], GPIO.HIGH)
time.sleep(5) # Run the green light for 5 seconds
# Switch on blue light
GPIO.output(led_pins["green"], GPIO.LOW)
GPIO.output(led_pins["blue"], GPIO.HIGH)
time.sleep(2) # Run the blue light for 2 seconds
# Switch off all lights
GPIO.output(led_pins["red"], GPIO.LOW)
GPIO.output(led_pins["blue"], GPIO.LOW)
# Call the traffic_light function
traffic_light()
# Clean up GPIO pins
GPIO.cleanup()
In this example, we need to install the RPi.GPIO library to control the GPIO pins on a Raspberry Pi. If you're not using a Raspberry Pi, you can adapt the code accordingly.
Also, make sure to wire the LED lights to the appropriate GPIO pins as specified in the led_pins dictionary.
This code will light up the red LED for 5 seconds, then switch to the green LED for 5 seconds, and finally, switch to the blue LED for 2 seconds before turning off all LEDs.