0
0
Iot-protocolsProgramBeginner · 2 min read

Raspberry Pi Program for Traffic Light Control

Use the RPi.GPIO library to control GPIO pins for red, yellow, and green LEDs with timed delays; for example, set pins high and low in sequence with GPIO.output(pin, GPIO.HIGH) and time.sleep(seconds) to simulate a traffic light.
📋

Examples

InputRun the program with red=pin17, yellow=pin27, green=pin22
OutputRed LED on for 5 seconds, yellow LED on for 2 seconds, green LED on for 5 seconds, then repeats
InputChange timing to red=3s, yellow=1s, green=4s
OutputRed LED on for 3 seconds, yellow LED on for 1 second, green LED on for 4 seconds, then repeats
InputUse pins 5, 6, 13 for red, yellow, green LEDs
OutputTraffic light cycles on pins 5, 6, 13 with default timing
🧠

How to Think About It

To create a traffic light program on Raspberry Pi, connect three LEDs to GPIO pins representing red, yellow, and green lights. The program turns each LED on and off in the correct order with delays to simulate real traffic light timing. Use GPIO.output to control LEDs and time.sleep to wait between changes.
📐

Algorithm

1
Set up GPIO pins for red, yellow, and green LEDs as outputs
2
Turn on red LED and turn off others, wait for red light duration
3
Turn on yellow LED and turn off others, wait for yellow light duration
4
Turn on green LED and turn off others, wait for green light duration
5
Repeat the cycle indefinitely
6
Clean up GPIO pins on program exit
💻

Code

raspberry_pi
import RPi.GPIO as GPIO
import time

# Define GPIO pins
RED = 17
YELLOW = 27
GREEN = 22

# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(RED, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(GREEN, GPIO.OUT)

try:
    while True:
        GPIO.output(RED, GPIO.HIGH)
        GPIO.output(YELLOW, GPIO.LOW)
        GPIO.output(GREEN, GPIO.LOW)
        print("Red ON")
        time.sleep(5)

        GPIO.output(RED, GPIO.LOW)
        GPIO.output(YELLOW, GPIO.HIGH)
        GPIO.output(GREEN, GPIO.LOW)
        print("Yellow ON")
        time.sleep(2)

        GPIO.output(RED, GPIO.LOW)
        GPIO.output(YELLOW, GPIO.LOW)
        GPIO.output(GREEN, GPIO.HIGH)
        print("Green ON")
        time.sleep(5)

except KeyboardInterrupt:
    print("Program stopped")
finally:
    GPIO.cleanup()
Output
Red ON Yellow ON Green ON Red ON Yellow ON Green ON ... (repeats until stopped)
🔍

Dry Run

Let's trace one full cycle of the traffic light program through the code.

1

Turn on Red LED

GPIO.output(RED, GPIO.HIGH) sets pin 17 high; Red LED lights up. Yellow and Green pins set low, LEDs off.

2

Wait for 5 seconds

time.sleep(5) pauses the program, keeping Red LED on.

3

Turn on Yellow LED

GPIO.output(YELLOW, GPIO.HIGH) sets pin 27 high; Yellow LED lights up. Red and Green LEDs off.

4

Wait for 2 seconds

time.sleep(2) pauses the program, keeping Yellow LED on.

5

Turn on Green LED

GPIO.output(GREEN, GPIO.HIGH) sets pin 22 high; Green LED lights up. Red and Yellow LEDs off.

6

Wait for 5 seconds

time.sleep(5) pauses the program, keeping Green LED on.

StepRed PinYellow PinGreen PinLED On
1HIGHLOWLOWRed
2HIGHLOWLOWRed (waiting)
3LOWHIGHLOWYellow
4LOWHIGHLOWYellow (waiting)
5LOWLOWHIGHGreen
6LOWLOWHIGHGreen (waiting)
💡

Why This Works

Step 1: GPIO Setup

We use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom numbers and set each LED pin as output with GPIO.setup(pin, GPIO.OUT).

Step 2: Control LEDs

Turning an LED on means setting its pin to GPIO.HIGH and turning others off with GPIO.LOW to simulate traffic light states.

Step 3: Timing with sleep

We use time.sleep(seconds) to keep each LED on for the correct duration, mimicking real traffic light timing.

🔄

Alternative Approaches

Using PWM for brightness control
raspberry_pi
import RPi.GPIO as GPIO
import time

RED = 17
YELLOW = 27
GREEN = 22

GPIO.setmode(GPIO.BCM)
GPIO.setup(RED, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(GREEN, GPIO.OUT)

red_pwm = GPIO.PWM(RED, 100)
yellow_pwm = GPIO.PWM(YELLOW, 100)
green_pwm = GPIO.PWM(GREEN, 100)

red_pwm.start(0)
yellow_pwm.start(0)
green_pwm.start(0)

try:
    while True:
        red_pwm.ChangeDutyCycle(100)
        yellow_pwm.ChangeDutyCycle(0)
        green_pwm.ChangeDutyCycle(0)
        print("Red ON with PWM")
        time.sleep(5)

        red_pwm.ChangeDutyCycle(0)
        yellow_pwm.ChangeDutyCycle(100)
        green_pwm.ChangeDutyCycle(0)
        print("Yellow ON with PWM")
        time.sleep(2)

        red_pwm.ChangeDutyCycle(0)
        yellow_pwm.ChangeDutyCycle(0)
        green_pwm.ChangeDutyCycle(100)
        print("Green ON with PWM")
        time.sleep(5)

except KeyboardInterrupt:
    print("Program stopped")
finally:
    red_pwm.stop()
    yellow_pwm.stop()
    green_pwm.stop()
    GPIO.cleanup()
This method allows smooth brightness control but is more complex and uses more CPU.
Using a state machine with a dictionary
raspberry_pi
import RPi.GPIO as GPIO
import time

RED = 17
YELLOW = 27
GREEN = 22

GPIO.setmode(GPIO.BCM)
GPIO.setup(RED, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(GREEN, GPIO.OUT)

states = [
    {'red': True, 'yellow': False, 'green': False, 'duration': 5},
    {'red': False, 'yellow': True, 'green': False, 'duration': 2},
    {'red': False, 'yellow': False, 'green': True, 'duration': 5}
]

try:
    while True:
        for state in states:
            GPIO.output(RED, GPIO.HIGH if state['red'] else GPIO.LOW)
            GPIO.output(YELLOW, GPIO.HIGH if state['yellow'] else GPIO.LOW)
            GPIO.output(GREEN, GPIO.HIGH if state['green'] else GPIO.LOW)
            print(f"State: Red={state['red']}, Yellow={state['yellow']}, Green={state['green']}")
            time.sleep(state['duration'])

except KeyboardInterrupt:
    print("Program stopped")
finally:
    GPIO.cleanup()
This approach is more scalable and easier to modify states but uses more memory.

Complexity: O(1) time, O(1) space

Time Complexity

The program runs in an infinite loop with fixed delays; no loops depend on input size, so time complexity is constant O(1).

Space Complexity

Only a few variables and GPIO pin states are stored, so space complexity is constant O(1).

Which Approach is Fastest?

All approaches run in real time with delays; the basic GPIO on/off method uses least CPU, while PWM uses more CPU for brightness control.

ApproachTimeSpaceBest For
Basic GPIO On/OffO(1)O(1)Simple, low CPU usage
PWM Brightness ControlO(1)O(1)Smooth LED brightness, more complex
State Machine DictionaryO(1)O(1)Easily extendable and modifiable states
💡
Always use GPIO.cleanup() to reset pins when your program ends to avoid warnings.
⚠️
Beginners often forget to set GPIO mode or pins as output, causing LEDs not to light up.