Programming a Traffic Light with Arduino: Learning the State Machine

Engineering illustration: Programming a Traffic Light with Arduino: Learning the State Machine

The traffic light project is one of the most popular teaching projects for learning the "state machine" concept in programming, where the system moves through three sequential states, each with its own fixed timing.

Components needed

An Arduino Uno board, and a ready-made traffic light module with three LEDs (red, yellow, and green), or three separate LEDs with 220-ohm resistors.

Wiring it up

The red LED connects to digital pin 2, yellow to pin 3, and green to pin 4. A ready-made module works directly off the Arduino's 5V without extra resistors if they're already built in.

How it works

Rather than using delay() directly, which halts the rest of the code's execution, a well-designed version of this project relies on a simple state machine that tracks elapsed time since each phase began using millis(). The signal moves through three consecutive phases: a green phase lasting 5000 milliseconds allowing traffic to move, followed by a yellow phase lasting 2000 milliseconds as a warning to prepare to stop, then a red phase lasting 5000 milliseconds that stops movement entirely, after which the cycle starts over. Using millis() instead of delay() makes it possible to later extend the project to control more than one traffic intersection at the same time without timing conflicts.

You can find ready-made traffic light modules and LEDs at Juthour Tech.

اترك تعليقا

*
*
يمكن للأعضاء المسجلين فقط ترك تعليقات.