Traffic Light
Build a working traffic light with three LEDs (red, yellow, green) driven by a Raspberry Pi and Pi4J.
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
- Connect each LED's anode (longer leg) to a distinct GPIO pin through a 220Ω resistor.
- Connect all cathodes (shorter legs) to any GND pin on the Pi.
- 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:
- Green — traffic can pass. Long duration.
- Yellow — get ready to stop. Short duration.
- Red — traffic stops. Long duration.
- 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.