</>EmbeddedInterview

Implement a finite state machine for a device driver.

Medium"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>

typedef enum { DRV_OFF, DRV_INIT, DRV_IDLE, DRV_BUSY, DRV_ERROR } drv_state_t;
typedef enum { EV_POWER_ON, EV_INIT_OK, EV_INIT_FAIL, EV_START, EV_DONE, EV_FAULT, EV_RESET } drv_event_t;

typedef struct { drv_state_t state; uint8_t retries; } drv_t;

void hw_power_on(void); void hw_start_transfer(void); void hw_reset(void); void report(int err);

void drv_handle(drv_t *d, drv_event_t ev)
{
    switch (d->state) {
    case DRV_OFF:
        if (ev == EV_POWER_ON) { hw_power_on(); d->retries = 0; d->state = DRV_INIT; }
        break;
    case DRV_INIT:
        if (ev == EV_INIT_OK) d->state = DRV_IDLE;
        else if (ev == EV_INIT_FAIL) {
            if (++d->retries < 3) hw_power_on();           /* retry */
            else { report(1); d->state = DRV_ERROR; }
        }
        break;
    case DRV_IDLE:
        if (ev == EV_START) { hw_start_transfer(); d->state = DRV_BUSY; }
        break;
    case DRV_BUSY:
        if (ev == EV_DONE) d->state = DRV_IDLE;
        else if (ev == EV_FAULT) { report(2); d->state = DRV_ERROR; }
        break;
    case DRV_ERROR:
        if (ev == EV_RESET) { hw_reset(); d->retries = 0; d->state = DRV_INIT; }
        break;
    }
    /* events not handled in a state are ignored here; log them in real code */
}

Points: the driver's API calls and interrupts become events; the state decides what is legal (e.g. EV_START is ignored or rejected unless IDLE); errors move to a recovery state with limited retries; the state is per device instance (a struct), so several devices can share the code. Feed events from ISRs through a queue so the FSM runs in one context.