Simvik

State handlers

Build a state machine in which each state is a function. A hard embedded C problem (Function pointers and state machines), run and graded in the browser.

hard · Function pointers and state machines · state-machine · function-pointers

Implement a pedestrian crossing in the state-pattern style: the object stores a pointer to the handler of its current state, and dispatching an event simply calls it.

  • Green ('G'): on EV_BUTTON, go to yellow. Ticks are ignored.
  • Yellow ('Y'): after 2 ticks, go to red. The button is ignored.
  • Red ('R'): after 3 ticks, go to green. The button is ignored.

Entering a state sets lamp and resets ticks to 0. Write light_init, which starts in green, and light_dispatch, which delivers one event.

Starter code

// Write one handler function per state, then:

void light_init(light_t *l) {
  // Start in green: set l->state, l->lamp and l->ticks.
}

void light_dispatch(light_t *l, event_t ev) {
  // Hand the event to the current state's handler.
}

Example tests

Green until the button is pressed

light_t l;
light_init(&l);
putchar(l.lamp);
putchar('\n');
feed(&l, "TB");

Expected output:

G
GY

One full cycle

light_t l;
light_init(&l);
feed(&l, "BTTTTT");

Expected output:

YYRRRG

Learn it first

More Function pointers and state machines problems