Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Traffic Light State Machine

Design a safe traffic light controller in Ada: enumeration states, a transition function with contracts, a periodic task and safety properties, with a runnable C simulation.

State machines are everywhere in embedded and safety-critical software, and Ada fits them well: enumeration types name the states, case statements must cover every state, and contracts describe the legal transitions. In this project you design a traffic light controller for a crossing of two roads, and state the safety rule that the two roads never both get green.

The Ada code is read-only on this site (no compiler). The C program is a runnable simulation that checks the same design.

States and transitions

Each road cycles through green, yellow, red. To keep it simple, we model the crossing as one machine with four phases. The all red phases give cars time to clear the junction.

Four phases

North-South go NS green, EW red
NS clearing NS yellow, EW red
East-West go EW green, NS red
EW clearing EW yellow, NS red

After clearing, the other road gets green.

1 / 2
stateDiagram-v2
    [*] --> NS_Go
    NS_Go --> NS_Clear : timer
    NS_Clear --> EW_Go : timer
    EW_Go --> EW_Clear : timer
    EW_Clear --> NS_Go : timer

The controller moves to the next phase whenever the timer expires.

The Ada design

Enumerations make illegal states unrepresentable, and a subtype-style contract makes the rule explicit.

ADA
package Traffic is

   type Phase is (NS_Go, NS_Clear, EW_Go, EW_Clear);
   type Light is (Red, Yellow, Green);

   function North_South (P : Phase) return Light is
     (case P is
        when NS_Go    => Green,
        when NS_Clear => Yellow,
        when EW_Go | EW_Clear => Red);

   function East_West (P : Phase) return Light is
     (case P is
        when EW_Go    => Green,
        when EW_Clear => Yellow,
        when NS_Go | NS_Clear => Red);

   function Next (P : Phase) return Phase is
     (if P = Phase'Last then Phase'First else Phase'Succ (P))
     with Post => Next'Result /= P;

   function Safe (P : Phase) return Boolean is
     (not (North_South (P) = Green and East_West (P) = Green));

end Traffic;

The case expression must list every Phase, so adding a fifth phase later makes the compiler flag each function that needs updating. Safe states the rule, and with assertions enabled you can use it as a postcondition on the step procedure:

ADA
procedure Step (P : in out Phase)
  with Post => Safe (P) and P = Next (P'Old);

In SPARK, the prover can show Safe holds for all four phases by case analysis (a tiny proof), and that Step never skips a phase.

The controller task

ADA
with Ada.Real_Time; use Ada.Real_Time;
with Traffic;       use Traffic;

task Controller;

task body Controller is
   Current : Phase := NS_Go;
   Next_At : Time  := Clock;

   function Duration_Of (P : Phase) return Time_Span is
     (case P is
        when NS_Go | EW_Go       => Seconds (30),
        when NS_Clear | EW_Clear => Seconds (4));
begin
   loop
      Set_Lights (North_South (Current), East_West (Current));
      Next_At := Next_At + Duration_Of (Current);
      delay until Next_At;
      Current := Next (Current);
   end loop;
end Controller;

delay until prevents drift, and Duration_Of gives green phases 30 seconds and clearing phases 4 seconds. Set_Lights would write to hardware registers (see embedded Ada). A real intersection would add a watchdog and a fail-safe mode of flashing red, because the safest response to an internal fault is to put all lights in a known safe state.

C simulation

The simulation steps the machine through two full cycles using virtual time, prints each phase, and checks the safety rule after every step. It also checks that a corrupted phase value (outside the enumeration) is treated as a fault, the role Ada's range checks play.

C C simulation: phases, durations and the safety rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output ends with cycle length: 68 s, unsafe phases seen: 0 because each cycle is 30 + 4 + 30 + 4 = 68 seconds.

Exhaustive check of the rule

For a machine with only four states you can test every state and every transition. The second program checks that each phase is safe, that next visits all four phases in a loop, and that no transition goes from one green phase straight to the other.

C C simulation: exhaustive transition check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Extensions

  • Add a pedestrian request through a protected object that shortens the current green phase.
  • Add a Fault phase that flashes red, entered through an exception handler or a failed Safe check.
  • Make durations configurable with a record and a Dynamic_Predicate that ensures every clearing time is at least 3 seconds.
  • Prove Safe with SPARK, as described in Proving Absence of Run-Time Errors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use an enumeration type and a case expression for the phases?

    Ada requires case choices to cover all values, so incomplete handling is a compile-time error.
  2. 2. What does the Safe function express?

    It is the safety invariant used as a postcondition.
  3. 3. Why does the controller use delay until?

    Adding durations to an absolute time keeps the schedule exact.
  4. 4. What is a sensible reaction to an internal fault in a traffic controller?

    Fail-safe design chooses a state that cannot cause a collision.

Summary

  • Enumerations plus exhaustive case expressions make state machines robust against forgotten states.
  • A Safe predicate states the safety rule once and can be used as a contract or proved.
  • A periodic task with delay until drives the transitions without drift.
  • With only four states, exhaustive testing is feasible and the C simulation does it.
  • Real controllers add fault handling and a fail-safe state.

Next: Practice: Ada Concepts Review