</>EmbeddedInterview

Implement a state machine for a traffic light.

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

typedef enum { RED, RED_AMBER, GREEN, AMBER } light_t;

typedef struct { light_t next; uint32_t duration_ms; uint8_t lamps; } state_info_t;
#define L_RED 4u
#define L_AMB 2u
#define L_GRN 1u

static const state_info_t fsm[] = {
    [RED]       = { RED_AMBER, 20000, L_RED },
    [RED_AMBER] = { GREEN,      2000, L_RED | L_AMB },
    [GREEN]     = { AMBER,     20000, L_GRN },
    [AMBER]     = { RED,        3000, L_AMB },
};

void set_lamps(uint8_t mask);
extern volatile uint32_t g_ms;

void traffic_light_task(void)                     /* call often from the main loop */
{
    static light_t state = RED;
    static uint32_t entered;
    static int started;
    if (!started) { started = 1; entered = g_ms; set_lamps(fsm[state].lamps); }
    if ((uint32_t)(g_ms - entered) >= fsm[state].duration_ms) {
        state = fsm[state].next;
        entered = g_ms;
        set_lamps(fsm[state].lamps);              /* entry action */
    }
}

Points: a const table describes states, durations and outputs (easy to check against the specification); timing uses timestamps, not blocking delays; outputs are set on state entry. Extensions interviewers ask for: a pedestrian button (an event that shortens GREEN), a fault state (flashing amber) entered on lamp failure, and a safe start-up state (all red).