Simvik

Fix: the door opens by itself

A door controller skips its unlocking state. An easy embedded C problem (State machines), run and graded in the browser.

easy · State machines · find-the-bug · switch · state-machine

Bug report. Field units sometimes swing the door open when nobody has pressed the button. The event log shows the controller jumping from LOCKED straight to OPEN; the UNLOCKING state, which releases the bolt first, never appears.

door_step runs once per tick. From LOCKED it moves to UNLOCKING only when button is pressed, otherwise it stays LOCKED. UNLOCKING always moves to OPEN, and OPEN always moves back to LOCKED. Find the defect and fix it by changing one line.

Starter code

door_t door_step(door_t s, bool button) {
  switch (s) {
    case LOCKED:
      if (button) s = UNLOCKING;
    case UNLOCKING:
      s = OPEN;
      break;
    case OPEN:
      s = LOCKED;
      break;
  }
  return s;
}

Example tests

One press among idle ticks

run("..B...");

Expected output:

LOCKED LOCKED UNLOCKING OPEN LOCKED LOCKED

Learn it first

More State machines problems