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 forticksticks.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 andpostanEV_TIMEOUTcarrying the currenttimer_gen.pump_dispatch(p, e): handle one event.
| State | Event | Action | Next |
|---|---|---|---|
| idle | START | motor on, timer 3 | priming |
| priming | FLOW_OK | cancel timer | running |
| priming | TIMEOUT | motor off | fault |
| running | FLOW_LOST | timer 3 (motor stays on) | priming |
| priming, running | STOP | motor off, cancel timer | idle |
| fault | RESET | idle |
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=1No flow means a dry-run fault
run("s . . . r");Expected output:
PPPFI motor=0Flow flickers just as the timer expires
run("s . . fl . . . r");Expected output:
PPPPPPFI motor=0Learn it first
- Event-driven state machines · From polling to events, queues and run-to-completion.
More Event-driven state machines problems
- Defer events until the machine is ready · Hold START requests that arrive while busy, and replay them when idle.
- Train doors: safe in any order of events · A door controller that reverses on an obstacle and never opens while the train moves.