This low-voltage model uses LEDs and a button to demonstrate state machines, event handling, non-blocking timing and predictable sequences. It is an educational tabletop model, not a certified traffic-control device.
Arduino sketch: non-blocking state machine
const byte redPin = 8;
const byte amberPin = 9;
const byte greenPin = 10;
const byte requestPin = 2;
enum State { VEHICLE_GREEN, VEHICLE_AMBER,
PEDESTRIAN_RED, RETURN_AMBER };
State state = VEHICLE_GREEN;
const unsigned long greenMinMs = 3000;
const unsigned long amberMs = 1500;
const unsigned long crossingMs = 4000;
unsigned long stateStarted = 0;
bool requestPending = false;
bool previousButton = HIGH;
void showLamps(bool red, bool amber, bool green) {
digitalWrite(redPin, red);
digitalWrite(amberPin, amber);
digitalWrite(greenPin, green);
}
void enterState(State next, unsigned long now) {
state = next;
stateStarted = now;
switch (state) {
case VEHICLE_GREEN: showLamps(LOW, LOW, HIGH); break;
case VEHICLE_AMBER: showLamps(LOW, HIGH, LOW); break;
case PEDESTRIAN_RED: showLamps(HIGH, LOW, LOW); break;
case RETURN_AMBER: showLamps(LOW, HIGH, LOW); break;
}
}
void setup() {
pinMode(redPin, OUTPUT);
pinMode(amberPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(requestPin, INPUT_PULLUP);
enterState(VEHICLE_GREEN, millis());
}
void loop() {
unsigned long now = millis();
bool button = digitalRead(requestPin);
if (previousButton == HIGH && button == LOW)
requestPending = true;
previousButton = button;
switch (state) {
case VEHICLE_GREEN:
if (requestPending &&
now - stateStarted >= greenMinMs) {
requestPending = false;
enterState(VEHICLE_AMBER, now);
}
break;
case VEHICLE_AMBER:
if (now - stateStarted >= amberMs)
enterState(PEDESTRIAN_RED, now);
break;
case PEDESTRIAN_RED:
if (now - stateStarted >= crossingMs)
enterState(RETURN_AMBER, now);
break;
case RETURN_AMBER:
if (now - stateStarted >= amberMs)
enterState(VEHICLE_GREEN, now);
break;
}
}
Educational sequence only. This sketch omits certified pedestrian indicators, conflict monitoring, fault-tolerant lamp drivers, independent safety circuits and formal timing validation. It must not control a real road crossing.