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 LOCKEDLearn it first
- State machine patterns in C · Switch, transition tables and state-function pointers compared.
More State machines problems
- Traffic light with a fault mode · Write the transition function for a light that cycles, flashes on a fault and resets.
- 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.
- Washing machine: the cycle and the door · Run a wash cycle as a state machine that pauses safely when the door opens.