Washing machine: the cycle and the door
Run a wash cycle as a state machine that pauses safely when the door opens. A medium embedded C problem (State machines), run and graded in the browser.
medium · State machines · state-machine · safety · product
Product: Washing machine (Consumer electronics)
Requirement. The machine goes IDLE → FILL → WASH → RINSE → SPIN → DONE: START begins filling, FULL (the water level switch) starts the wash, and TIMER ends the wash, the rinse and the spin. Opening the door when DONE goes back to IDLE.
Safety. If the door opens while filling, washing, rinsing or spinning, go to PAUSED and remember where you were. Closing the door resumes exactly there. While PAUSED, nothing else does anything.
Any other event in any state is ignored (the state stays the same). Return the next state; *resume is where you keep the state to resume.
Starter code
state_t washer_step(state_t s, event_t e, state_t *resume) {
switch (s) {
case IDLE: return e == EV_START ? FILL : IDLE;
case FILL: return e == EV_FULL ? WASH : FILL;
case WASH: return e == EV_TIMER ? RINSE : WASH;
case RINSE: return e == EV_TIMER ? SPIN : RINSE;
case SPIN: return e == EV_TIMER ? DONE : SPIN;
case DONE: return e == EV_DOOR_OPEN ? IDLE : DONE;
case PAUSED: return PAUSED;
}
return s;
}Example tests
A whole cycle
const char *name[] = { "idle", "fill", "wash", "rinse", "spin", "done", "paused" };
event_t ev[] = { EV_START, EV_FULL, EV_TIMER, EV_TIMER, EV_TIMER, EV_DOOR_OPEN };
state_t s = IDLE, r = IDLE;
for (int i = 0; i < 6; i++) { s = washer_step(s, ev[i], &r); printf("%s ", name[s]); }
printf("\n");Expected output:
fill wash rinse spin done idleThe door opens during the wash
const char *name[] = { "idle", "fill", "wash", "rinse", "spin", "done", "paused" };
event_t ev[] = { EV_START, EV_FULL, EV_DOOR_OPEN, EV_TIMER, EV_DOOR_CLOSED, EV_TIMER };
state_t s = IDLE, r = IDLE;
for (int i = 0; i < 6; i++) { s = washer_step(s, ev[i], &r); printf("%s ", name[s]); }
printf("\n");Expected output:
fill wash paused paused wash rinseLearn 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.
- Fix: the door opens by itself · A door controller skips its unlocking state.