Skip to content
Tactiverge

Super-loops and finite state machines

How most firmware is structured as a loop that runs forever, and how a finite state machine keeps complicated behaviour clear, testable and safe.

Lesson 4 of 6 · 30 min · Self-paced · Free

Structure before features

A robot gripper must close when asked, stop when it is holding firmly, release on command, and refuse to keep squeezing if something goes wrong. Written as a pile of if statements and flags, this logic quickly becomes a tangle that nobody, including its author, can reason about. Two simple structures, the super-loop and the finite state machine, keep firmware understandable as it grows. They are used in a huge range of real embedded products.

The super-loop

Most bare-metal firmware has the same shape: set things up once, then loop forever.

/* Illustrative structure: the four functions are your own code. */
int main(void) {
    setup_hardware();        /* runs once after reset */
    while (1) {              /* runs forever */
        read_inputs();       /* sample buttons, sensors, messages */
        update_logic();      /* decide what to do */
        write_outputs();     /* drive LEDs, motors, displays */
    }
}

This is the super-loop. It is the sense–think–act loop from robotics foundations, written in C. Its strengths are simplicity and predictability: there is no operating system, and you can see everything the chip does. Its main rule is that nothing inside the loop may take long, because while one part is busy, every other part waits. The next lesson shows how to wait without blocking.

Separating the three phases also helps. If update_logic works only with values that read_inputs has stored, and produces values that write_outputs applies, the logic can be tested on a laptop with made-up inputs, no hardware needed.

Why flags get messy

Imagine writing the gripper logic with flags: is_closing, is_holding, is_opening, has_fault. Four true/false flags allow 2^4 = 16 combinations. Most are meaningless: closing and opening at once? Holding and faulted? Each one is a bug waiting to happen. What we really mean is that the gripper is in exactly one situation at a time.

Finite state machines

A finite state machine (FSM) has:

  • a fixed list of states, of which exactly one is current;
  • inputs or events that the machine responds to;
  • transitions: rules saying which event moves it from one state to another;
  • actions: what the outputs do in each state or on each transition.

Here is the gripper as a state machine, written as a list of transitions:

IDLE     --close command-->        CLOSING
CLOSING  --force reached-->        HOLDING
CLOSING  --2 s without force-->    FAULT
HOLDING  --open command-->         OPENING
OPENING  --fully open switch-->    IDLE
FAULT    (stays until a person resets the system)

Drawing this as circles and arrows on paper before writing code is one of the best habits you can build. Every arrow should have a label; every state should say what happens to unexpected events.

The timeout from CLOSING to FAULT is a safety feature. If the object slips out or a sensor fails, the gripper must not squeeze forever. State machines make such rules explicit and easy to review.

Writing it in C

An enum names the states and a switch statement handles each one. The decision logic is a pure function: it takes the current state and inputs, returns the next state, and touches no hardware. This portable program simulates it with a made-up script of inputs, one step every 100 ms:

#include <stdio.h>

typedef enum { IDLE, CLOSING, HOLDING, OPENING, FAULT } State;
static const char *state_name[] = { "IDLE", "CLOSING", "HOLDING", "OPENING", "FAULT" };

typedef struct {
    int close_cmd;    /* 1 = asked to grip */
    int open_cmd;     /* 1 = asked to release */
    int force_ok;     /* 1 = grip force has reached its target */
    int fully_open;   /* 1 = jaws are at the open limit switch */
} Inputs;

#define CLOSE_TIMEOUT_MS 2000

/* Pure function: current state + inputs + time in state -> next state. */
State next_state(State s, const Inputs *in, int ms_in_state) {
    switch (s) {
    case IDLE:
        return in->close_cmd ? CLOSING : IDLE;
    case CLOSING:
        if (in->force_ok) return HOLDING;
        if (ms_in_state >= CLOSE_TIMEOUT_MS) return FAULT;
        return CLOSING;
    case HOLDING:
        return in->open_cmd ? OPENING : HOLDING;
    case OPENING:
        return in->fully_open ? IDLE : OPENING;
    case FAULT:
        return FAULT;   /* stays here until a person resets the system */
    }
    return FAULT;       /* unknown state: fail safe */
}

int main(void) {
    State s = IDLE;
    int ms_in_state = 0;

    /* Made-up test script, one step every 100 ms. */
    for (int t = 0; t <= 5000; t += 100) {
        Inputs in = {0, 0, 0, 0};
        if (t == 300 || t == 2200) in.close_cmd = 1;
        if (t >= 900 && t < 1500)  in.force_ok = 1;
        if (t == 1500)             in.open_cmd = 1;
        if (t >= 1900 && t < 2100) in.fully_open = 1;

        State n = next_state(s, &in, ms_in_state);
        if (n != s) {
            printf("t=%4d ms  %-7s -> %s\n", t, state_name[s], state_name[n]);
            s = n;
            ms_in_state = 0;
        } else {
            ms_in_state += 100;
        }
    }
    return 0;
}

Output:

t= 300 ms  IDLE    -> CLOSING
t= 900 ms  CLOSING -> HOLDING
t=1500 ms  HOLDING -> OPENING
t=1900 ms  OPENING -> IDLE
t=2200 ms  IDLE    -> CLOSING
t=4300 ms  CLOSING -> FAULT

The first cycle works normally. In the second, the force sensor never reports success, so the timeout fires and the gripper enters FAULT. (It fires at 4,300 ms rather than 4,200 ms because this simple counter starts at zero on entry and is only checked once per 100 ms step. Off-by-one-step details like this are exactly what desktop tests reveal.)

Good habits for state machines

  • One variable holds the state. No separate flags that can disagree.
  • Every state handles every input, even if the answer is "stay here". The return FAULT after the switch catches a corrupted or unknown state and fails safe.
  • Outputs follow from the state. In write_outputs, the motor runs forward only in CLOSING, backward only in OPENING, and is off in every other state. Then the outputs can never contradict the state.
  • Test on a desktop first. Because next_state touches no hardware, you can run hundreds of scripted scenarios, including rare faults, before the code ever moves a real motor.

Project

Design a state machine for a robot charging dock

A small mobile robot drives back to a charging dock when its stored charge is low. Design the firmware's state machine.

  1. On paper, draw states such as WORKING, RETURNING, DOCKING, CHARGING and FAULT, with labelled arrows for events like "charge below 20 %", "dock in sight", "contacts touching", "fully charged" and timeouts.
  2. Decide what happens if the dock is not found within 60 seconds.
  3. Write next_state in C99 using an enum and switch, adapting the gripper example.
  4. Write a scripted test in main with made-up inputs that exercises at least one normal charge cycle and one fault, and print every transition.

This is a paper and software activity; no hardware is needed.

Deliverables

  • A labelled state diagram with every transition named
  • Your next_state function, compiled with cc -std=c99 -Wall without warnings
  • Printed transitions from your scripted test, covering a normal cycle and a fault

Knowledge check

Check your understanding

  1. 1. What is the most important rule for code inside a super-loop?
  2. 2. Why is a single state variable better than four separate true/false flags for the gripper?
  3. 3. In the gripper machine, what is the purpose of the CLOSING-to-FAULT timeout?
  4. 4. Why is next_state written as a pure function that touches no hardware?

Go further

Super-loops and finite state machines — Embedded Systems — Tactiverge