Simvik

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 idle

The 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 rinse

Learn it first

More State machines problems