Traffic light with a fault mode
Write the transition function for a light that cycles, flashes on a fault and resets. An easy embedded C problem (State machines), run and graded in the…
easy · State machines · fsm · switch
Return the next state of a traffic light given its current state and an event:
EV_FAULTswitches toFLASHINGfrom any state.EV_RESETswitches toREDfrom any state.EV_TIMERcyclesREDtoGREENtoYELLOWand back toRED, and does nothing whileFLASHING.
Starter code
light_t light_next(light_t s, event_t e) {
switch (s) {
case RED: return GREEN;
case GREEN: return YELLOW;
case YELLOW: return RED;
default: return s;
}
}Example tests
Normal cycle
run(RED, "ttt");Expected output:
GREEN YELLOW REDFault and reset
run(GREEN, "ftr");Expected output:
FLASHING FLASHING REDLearn it first
- State machine patterns in C · Switch, transition tables and state-function pointers compared.
More State machines problems
- Table-driven state machine · Look up a transition in a table, run its action and return the next state.
- Keypad code lock · Implement a door lock that takes a 4-digit code, re-locks, and locks out after three failures.
- Garage door controller · Write the transition function of a garage door, including the obstacle safety reversal.
- Click, double-click and long press · Turn a sampled button into click, double-click and long-press events with a state machine.
- Fix: the door opens by itself · A door controller skips its unlocking state.
- Washing machine: the cycle and the door · Run a wash cycle as a state machine that pauses safely when the door opens.