Simvik

Pump controller with timers

An event-driven state machine with a timeout, where a timeout already queued must not act after its timer was cancelled. A hard embedded C problem…

hard · Event-driven state machines · fsm · events · timers · event-queue

A pump must never run dry. When started, it primes: the motor runs and the flow sensor must report flow within 3 ticks, or the pump stops with a fault. Events go through a queue and are handled one at a time; a timer posts EV_TIMEOUT when it expires.

Write the timer and the state machine:

  • timer_start(p, ticks): start (or restart) the timer for ticks ticks.
  • timer_cancel(p): stop the timer.
  • timer_tick(p): called every tick. If the timer is running, count down; when it reaches 0, stop it and post an EV_TIMEOUT carrying the current timer_gen.
  • pump_dispatch(p, e): handle one event.
StateEventActionNext
idleSTARTmotor on, timer 3priming
primingFLOW_OKcancel timerrunning
primingTIMEOUTmotor offfault
runningFLOW_LOSTtimer 3 (motor stays on)priming
priming, runningSTOPmotor off, cancel timeridle
faultRESETidle

Every other combination is ignored. The catch: a timeout can already be in the queue when its timer is cancelled or restarted. Change timer_gen whenever the timer is started or cancelled, and ignore an EV_TIMEOUT whose gen is not the current one.

Starter code

void timer_start(pump_t *p, uint8_t ticks) {
}

void timer_cancel(pump_t *p) {
}

void timer_tick(pump_t *p) {
}

void pump_dispatch(pump_t *p, event_t e) {
  if (p->state == P_IDLE && e.type == EV_START) {
    motor(true);
    timer_start(p, 3);
    p->state = P_PRIMING;
  }
}

Example tests

Primes, then runs

run("s . f . .");

Expected output:

PPRRR motor=1

No flow means a dry-run fault

run("s . . . r");

Expected output:

PPPFI motor=0

Flow flickers just as the timer expires

run("s . . fl . . . r");

Expected output:

PPPPPPFI motor=0

Learn it first

More Event-driven state machines problems