Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Embedded C

State Machines in C

Design embedded behavior as finite state machines: switch-based and table-driven implementations in C, events, actions, debouncing a button and a traffic light example.

Embedded devices spend their lives reacting: a button is pressed, a byte arrives, a timer expires, a fault is detected. What a device should do depends on what it is currently doing. A microwave ignores the "start" button while its door is open; a UART parser interprets a byte differently when it is inside a packet than between packets. The cleanest way to organize this is a finite state machine (FSM): a fixed set of states, a set of events, and rules saying "in state S, on event E, do action A and move to state T".

State machines replace tangled flag variables (if (running && !paused && !error)) with something you can draw, test and reason about. They are the single most useful design pattern in firmware, and they run just as well on a 2 KB chip as on an RTOS.

Anatomy of a state machine

  • States: the situations the device can be in (IDLE, RUNNING, ERROR).
  • Events: things that happen (button pressed, timeout, byte received).
  • Transitions: (state, event) leads to a new state, optionally with an action.
  • Entry and exit actions: code that runs when entering or leaving a state (turn the motor on at entry to RUNNING).
  • Initial state: where it starts after reset.

A diagram is the best design tool. Here is a simple door-lock controller:

stateDiagram-v2
    [*] --> Locked
    Locked --> Unlocked: correct code
    Locked --> Locked: wrong code (count++)
    Locked --> Alarm: 3 wrong codes
    Unlocked --> Locked: timeout / lock button
    Alarm --> Locked: admin reset

Every arrow is one row in the code. If the diagram is complete, the code is complete.

Method 1: switch on the state

The most common way is an enum for the state and a switch that handles each state. Events are passed in as an argument (or read inside).

C
typedef enum { ST_IDLE, ST_RUNNING, ST_PAUSED } State;
typedef enum { EV_START, EV_PAUSE, EV_STOP } Event;

State handle(State s, Event e) {
    switch (s) {
    case ST_IDLE:    if (e == EV_START) return ST_RUNNING;                  break;
    case ST_RUNNING: if (e == EV_PAUSE) return ST_PAUSED;
                     if (e == EV_STOP)  return ST_IDLE;                     break;
    case ST_PAUSED:  if (e == EV_START) return ST_RUNNING;
                     if (e == EV_STOP)  return ST_IDLE;                     break;
    }
    return s;            // ignore events that make no sense in this state
}

Notice the last line: an event that does not apply is ignored, a safe default. Enable -Wswitch (part of -Wall) so adding a state without handling it triggers a warning; avoid a default: label so the compiler can tell you about missing cases.

C A start/pause/stop machine with switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Method 2: table-driven

When the machine grows (20 states, 30 events), nested switch statements become hard to read. A transition table stores the machine as data: a 2-D array indexed by state and event, holding the next state and an action function pointer. Adding a transition means adding a table entry, not code, and the table is easy to review against the diagram.

C
typedef struct { State next; void (*action)(void); } Transition;
static const Transition table[STATE_COUNT][EVENT_COUNT] = {
    [ST_IDLE]    = { [EV_START] = {ST_RUNNING, motor_on} },
    [ST_RUNNING] = { [EV_PAUSE] = {ST_PAUSED, motor_off}, [EV_STOP] = {ST_IDLE, motor_reset} },
    ...
};

Designated initializers leave unlisted entries zero, meaning "no transition". The dispatcher is tiny and never changes:

C
const Transition *t = &table[state][event];
if (t->valid) {
    if (t->action) t->action();
    state = t->next;
}

Zero is a valid state number, so the table cannot use "next state is 0" to mean "no transition". A separate valid field (or a sentinel state) settles it. Decide this up front; the example below uses a valid field.

C A traffic light as a table-driven machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Press time is a design variable: the pedestrian button during green jumps straight to amber. A real controller also guarantees a minimum green time, which is one more row or one more guard.

Events from the real world: debouncing a button

Mechanical switches bounce: for a few milliseconds the contact flickers between open and closed. A beginner's if (pin == 0) count++; registers a single press as many. A small state machine fixes it: require the input to be stable for several consecutive samples before accepting a change.

C Debounce state machine with a noisy button signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The machine only emits one PRESS and one RELEASE, no matter how noisy the input. This one pattern replaces countless hardware debounce capacitors.

Design tips

  1. Draw it first. A diagram with all states and events exposes missing transitions before you write code.
  2. Make every (state, event) pair deliberate: handle it, ignore it, or flag it as an error.
  3. Keep actions short and non-blocking. An FSM that calls delay() is not reactive. Use timers and events instead (Interrupts and Timers).
  4. Separate event sources from the machine: ISRs and polling code enqueue events (in a small ring buffer, see Static Allocation and Memory Pools); the main loop pulls events and runs the machine. That keeps ISRs short.
  5. One state variable per machine, one place that changes it. Scattered writes to state become unreadable.
  6. Test the machine on a PC. A pure function next_state(state, event) can be unit tested with hundreds of event sequences without hardware.
  7. Hierarchical state machines (statecharts) share common behavior among states; frameworks like QP implement them. Start flat; grow only when needed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the three essential ingredients of a finite state machine?

    An FSM is defined by its states, the events it reacts to and the transitions between them.
  2. 2. What is a good default when an event arrives that has no meaning in the current state?

    Ignoring unexpected events keeps the machine safe and predictable. Log it if that situation signals a bug.
  3. 3. Why use a table-driven state machine for a large design?

    Adding or changing behavior is a table edit, which scales better than nested switch statements.
  4. 4. How does a debounce state machine remove button noise?

    Short bounces never stay stable long enough to be accepted, so only the real press passes.

Summary

  • A finite state machine models behavior as states, events and transitions; it replaces tangled flags with something drawable and testable.
  • switch-based machines are simple and clear; table-driven machines scale and are easy to review.
  • Always decide what happens for unexpected events; avoid default: so the compiler warns about missing states.
  • Debouncing is a small state machine; keep actions non-blocking and let ISRs only post events.
  • Test the transition function on a PC before it ever touches hardware.

Next: Memory-Mapped Registers