A traffic light simulation helps us understand how traffic signals change colors to control cars and people safely.
0
0
Traffic light simulation in Raspberry Pi
Introduction
To learn how to control lights using a Raspberry Pi.
To practice programming with hardware like LEDs.
To create a simple model of real-world traffic signals for education.
To test timing and sequence control in electronics projects.
Syntax
Raspberry Pi
import time import RPi.GPIO as GPIO # Setup GPIO pins GPIO.setmode(GPIO.BCM) RED = 17 YELLOW = 27 GREEN = 22 GPIO.setup(RED, GPIO.OUT) GPIO.setup(YELLOW, GPIO.OUT) GPIO.setup(GREEN, GPIO.OUT) # Function to turn off all lights def all_off(): GPIO.output(RED, False) GPIO.output(YELLOW, False) GPIO.output(GREEN, False)
Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.
Set each LED pin as output with GPIO.setup(pin, GPIO.OUT).
Examples
Turn a specific light on or off by setting its pin True or False.
Raspberry Pi
GPIO.output(RED, True) # Turn red light on GPIO.output(RED, False) # Turn red light off
Pause the program to keep the light on for some time.
Raspberry Pi
time.sleep(3) # Wait for 3 seconds
Use a function to switch off all LEDs before changing the light.
Raspberry Pi
all_off() # Turn all lights offSample Program
This program cycles through red, green, and yellow lights using LEDs connected to a Raspberry Pi. It prints which light is on and waits the right amount of time. Press Ctrl+C to stop.
Raspberry Pi
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) RED = 17 YELLOW = 27 GREEN = 22 GPIO.setup(RED, GPIO.OUT) GPIO.setup(YELLOW, GPIO.OUT) GPIO.setup(GREEN, GPIO.OUT) def all_off(): GPIO.output(RED, False) GPIO.output(YELLOW, False) GPIO.output(GREEN, False) try: while True: # Red light on all_off() GPIO.output(RED, True) print("Red light ON") time.sleep(5) # Green light on all_off() GPIO.output(GREEN, True) print("Green light ON") time.sleep(5) # Yellow light on all_off() GPIO.output(YELLOW, True) print("Yellow light ON") time.sleep(2) except KeyboardInterrupt: print("Program stopped") all_off() GPIO.cleanup()
OutputSuccess
Important Notes
Make sure your LEDs are connected with proper resistors to avoid damage.
Use GPIO.cleanup() to reset pins when the program ends.
Press Ctrl+C in the terminal to stop the program safely.
Summary
Traffic light simulation uses LEDs and timing to mimic real traffic signals.
GPIO pins control the lights by turning them on and off.
Use loops and delays to cycle through the colors in order.