Controlling a traffic light with code

Computer Science · Key Stage 2 · The School

A real system, in code

A traffic light follows a strict order: red, red and amber, green, amber, back to red. A program controlling it just repeats this sequence. It waits a set time on each colour before moving to the next. This happens over and over, all day long. The order itself never varies, whatever the time of day.

Why timing matters

Each colour needs enough time to matter. Too short a green light and nobody gets through. Too short an amber and drivers do not have time to react. Getting timing wrong in code has a real, physical result at a real junction. A number changed by accident could genuinely put someone at risk.

Writing the sequence

RED for 5 seconds. RED AND AMBER for 2 seconds. GREEN for 5 seconds. AMBER for 2 seconds. Then back to RED. Written as a loop, this sequence repeats forever. That is exactly what a real traffic light does all day. Nobody restarts a traffic light each morning. The loop simply never stops.

Finding the bug

A simulated light goes straight from green to red with no amber warning at all. Reading the code shows the amber step was left out of the loop entirely. Adding it back in fixes the whole sequence, and drivers get their warning again. Running the simulation slowly, one step at a time, is often the fastest way to spot a missing step. A single missing line in a long loop can be very easy to overlook.

The School — all subjects · Knowledge map