← Back to projects
Traffic Light

Traffic Light

A traffic light is one of the most classic projects in physical computing. It uses three LEDs — red, yellow and green — cycling in a well-defined order. It is a great next step after learning how to blink and alternate LEDs, because the logic is a small state machine instead of a simple loop.

In this project we build a functioning traffic light using a Raspberry Pi and Pi4J.

Source code: projects/traffic-light/TrafficLight.java

What You Will Learn

  • How to control three independent LEDs from Java
  • How to model a small state machine with GPIO output
  • How different timings shape the "feel" of a traffic light
  • How to organize repeatable phases in a Pi4J program

Components

  • Raspberry Pi
  • 1 red LED
  • 1 yellow LED
  • 1 green LED
  • 3 × 220Ω resistors
  • Breadboard
  • Jumper wires

Wiring

  1. Connect each LED's anode (longer leg) to a distinct GPIO pin through a 220Ω resistor.
  2. Connect all cathodes (shorter legs) to any GND pin on the Pi.
  3. Double-check the polarity before powering the Pi.

How It Works

The program configures three GPIO pins as digital outputs. It then cycles through the classic phases:

  1. Green — traffic can pass. Long duration.
  2. Yellow — get ready to stop. Short duration.
  3. Red — traffic stops. Long duration.
  4. Back to green.

At any given moment only one LED is on. When a phase ends, its LED is turned off before the next one is turned on, exactly like a real traffic light controller.

Possible Enhancements

  • Add a pedestrian button that requests a red phase
  • Add a second traffic light for a crossing (they should always be complementary)
  • Blink the green a few times before turning yellow
  • Add a countdown displayed on an LCD or a set of extra LEDs
  • Make timings configurable from a properties file

Why It Matters

Traffic lights teach a fundamental idea in embedded systems: at any moment, the hardware is in exactly one state, and each state has a defined output and a defined transition. Once you internalize that, you can drive far more complex devices — vending machines, elevators, robots — with the same mental model.