Blog.

Building a Traffic Light Controller Using Raspberry Pi, GPIO, and LEDs – A Step-by-Step Guide

Profile
Christopher Mace

As part of a recent project at MMBBS Business School, we were tasked with creating a simple traffic light controller using a Raspberry Pi (RPi), GPIO pins, and LEDs. This project was an excellent way to apply our technical skills in hardware interfacing while learning the basics of how traffic management systems work.

In this blog post, I’ll guide you through the steps to recreate this project on your own Raspberry Pi using Python.

What You’ll Need:

Before diving into the code and setup, make sure you have the following:

  • Raspberry Pi (any model with GPIO pins): I used a Raspberry Pi 3 for this project.
  • LEDs (3 colors): Red, Yellow, and Green.
  • Resistors (330 ohms): To prevent the LEDs from burning out.
  • Breadboard and Jumper Wires: For connecting everything together.
  • Python (with RPi.GPIO library): We will be using Python to control the GPIO pins.
  • GPIO pins on the Raspberry Pi: We’ll connect each LED to different GPIO pins on the Pi.

Step 1: Hardware Setup

First, let’s wire everything up:

  1. LED Connections:
    • Red LED: Connect the positive (longer leg) to GPIO pin 17 and the negative (shorter leg) to a resistor, which should be connected to the ground (GND) of the Raspberry Pi.
    • Yellow LED: Connect the positive leg to GPIO pin 27 and the negative leg to another resistor, connected to GND.
    • Green LED: Connect the positive leg to GPIO pin 22 and the negative leg to a resistor, connected to GND.
  2. Resistors: Each LED should be connected in series with a 330-ohm resistor to prevent excess current from damaging the LEDs.
  3. GPIO Pins: We will use the Raspberry Pi’s GPIO pins to control the LEDs. For this project, we used GPIO pins 17, 27, and 22 for red, yellow, and green, respectively.

Once the wiring is complete, your setup should resemble the image below (you can visualize it with a breadboard and GPIO pins properly connected to the LEDs).

Step 2: Install Required Libraries

Before we start coding, ensure you have the RPi.GPIO library installed on your Raspberry Pi. Open a terminal and type:

sudo apt-get update
sudo apt-get install python3-rpi.gpio

This will allow you to control the GPIO pins on your Raspberry Pi.

Step 3: Writing the Python Code

Now, let’s get into the fun part: writing the Python code to simulate the traffic light cycle. Open a new Python file (let’s name it traffic_light.py) and start by importing the necessary libraries:

import RPi.GPIO as GPIO
import time

Next, set up the GPIO mode to BCM and define the GPIO pins for each LED:

# Set the GPIO mode to BCM (Broadcom pin-numbering)
GPIO.setmode(GPIO.BCM)

# Define GPIO pins for each LED
RED_PIN = 17
YELLOW_PIN = 27
GREEN_PIN = 22

# Set up each GPIO pin as an output
GPIO.setup(RED_PIN, GPIO.OUT)
GPIO.setup(YELLOW_PIN, GPIO.OUT)
GPIO.setup(GREEN_PIN, GPIO.OUT)

Step 4: Creating the Traffic Light Sequence

A traffic light cycle typically follows the pattern:

  • Red -> Yellow -> Green -> Yellow -> Red (Repeat)

We’ll create a function that simulates this traffic light cycle. Inside the function, we'll turn on each LED for the correct amount of time, and then turn it off before moving to the next one.

def traffic_light_cycle():
# Red Light
print("Red Light ON")
GPIO.output(RED_PIN, GPIO.HIGH) # Turn on Red LED
time.sleep(5) # Wait for 5 seconds
GPIO.output(RED_PIN, GPIO.LOW) # Turn off Red LED

# Yellow Light
print("Yellow Light ON")
GPIO.output(YELLOW_PIN, GPIO.HIGH) # Turn on Yellow LED
time.sleep(2) # Wait for 2 seconds
GPIO.output(YELLOW_PIN, GPIO.LOW) # Turn off Yellow LED

# Green Light
print("Green Light ON")
GPIO.output(GREEN_PIN, GPIO.HIGH) # Turn on Green LED
time.sleep(5) # Wait for 5 seconds
GPIO.output(GREEN_PIN, GPIO.LOW) # Turn off Green LED

# Yellow Light again
print("Yellow Light ON")
GPIO.output(YELLOW_PIN, GPIO.HIGH) # Turn on Yellow LED
time.sleep(2) # Wait for 2 seconds
GPIO.output(YELLOW_PIN, GPIO.LOW) # Turn off Yellow LED

Step 5: Main Program Loop

Now, we need to make the traffic light run in a continuous loop. At the end of the script, write the following code to keep the program running until you manually stop it:

try:
while True:
traffic_light_cycle()
except KeyboardInterrupt:
print("Program interrupted, cleaning up...")
finally:
GPIO.cleanup() # Reset GPIO pins to a safe state

This code will ensure that the traffic light cycle continues indefinitely until you stop the program with CTRL + C. The finally block ensures that the GPIO pins are reset to their default state when the program ends.

Step 6: Running the Program

Now that the code is ready, save the Python file and run it using the following command:

python3 traffic_light.py

You should see the LEDs simulate a traffic light cycle on your Raspberry Pi, with the red, yellow, and green LEDs turning on and off at the specified intervals.

Step 7: Debugging and Improvements

If everything is connected correctly, and you don’t see the expected results, double-check your wiring. Here are a few tips for troubleshooting:

  • Ensure the LEDs are wired properly with resistors.
  • Verify the GPIO pins in the code match the ones you’re using on the Raspberry Pi.
  • Ensure that the Raspberry Pi is correctly configured to use the GPIO library.

Conclusion

This simple traffic light controller project on a Raspberry Pi is a great way to get hands-on experience with both hardware and software. It shows how Python can interact with physical components like LEDs and how to control them using GPIO pins. You can further improve this project by adding more features such as pedestrian buttons or integrating it into a larger traffic simulation.

I hope this guide helps you set up your own traffic light system with the Raspberry Pi. If you have any questions or run into issues, feel free to leave a comment below!


More Stories

My Application Developer's Journey to Business School at MMBBS

As an application developer, I have always been in the world of code, algorithms, and problem-solving. The logical flow of writing software, developing systems ...

Profile
Christopher Mace