Simvik

Train doors: safe in any order of events

A door controller that reverses on an obstacle and never opens while the train moves. A medium embedded C problem (Event-driven state machines), run and…

medium · Event-driven state machines · state-machine · events · interlock · product

Product: Train door controller (Rail and transport)

Requirement. Events reach the door controller in any order: passengers' buttons, the obstacle sensor in the door edge, the motor's end-of-travel timer, and the train's speed signal.

  • LOCKED (moving): only STOPPED does anything, giving CLOSED. The open button is ignored.
  • CLOSED: OPEN_BTN starts OPENING; SPEED (the train starts moving) gives LOCKED.
  • OPENING: TIMER gives OPEN.
  • OPEN: CLOSE_BTN starts CLOSING.
  • CLOSING: TIMER gives CLOSED; OBSTACLE reverses to OPENING, so nobody is trapped.

Every other event leaves the state as it is. Return the next state.

Starter code

door_t door_step(door_t s, door_event_t e) {
  switch (s) {
    case LOCKED:  return e == EV_STOPPED ? CLOSED : e == EV_OPEN_BTN ? OPENING : LOCKED;
    case CLOSED:  return e == EV_OPEN_BTN ? OPENING : e == EV_SPEED ? LOCKED : CLOSED;
    case OPENING: return e == EV_TIMER ? OPEN : OPENING;
    case OPEN:    return e == EV_CLOSE_BTN ? CLOSING : OPEN;
    case CLOSING: return e == EV_TIMER ? CLOSED : CLOSING;
  }
  return s;
}

Example tests

A station stop

const char *name[] = { "locked", "closed", "opening", "open", "closing" };
door_event_t ev[] = { EV_STOPPED, EV_OPEN_BTN, EV_TIMER, EV_CLOSE_BTN, EV_TIMER, EV_SPEED };
door_t s = LOCKED;
for (int i = 0; i < 6; i++) { s = door_step(s, ev[i]); printf("%s ", name[s]); }
printf("\n");

Expected output:

closed opening open closing closed locked

A bag in the closing door

const char *name[] = { "locked", "closed", "opening", "open", "closing" };
door_event_t ev[] = { EV_CLOSE_BTN, EV_OBSTACLE, EV_TIMER };
door_t s = OPEN;
for (int i = 0; i < 3; i++) { s = door_step(s, ev[i]); printf("%s ", name[s]); }
printf("\n");

Expected output:

closing opening open

Learn it first

More Event-driven state machines problems