4  The state transition table

4.1 Defining the states

#ifndef APP_STATE_H
#define APP_STATE_H

#include <Arduino.h>

// States. These become the "rows" of the state transition table
enum State : uint8_t
{
  STATE_WAIT, // idle
  STATE_MEAS, // measuring
  STATE_MAX,
};

inline const char *state_name(State s)
{
  switch (s)
  {
  case STATE_WAIT: return "WAIT";
  case STATE_MEAS: return "MEAS";
  default: return "UNKNOWN";
  }
}

#endif // APP_STATE_H

As with EventId, the trailing STATE_MAX gives the number of states.

4.2 The handler type and the table

#ifndef APP_HANDLER_H
#define APP_HANDLER_H

#include "app_event.h"
#include "app_state.h"

// Handler: receives an event and returns the next state
typedef State (*EventHandler)(const Event &ev);

// State transition table [state][event]. nullptr means "ignore that event in this state"
extern const EventHandler handler_table[STATE_MAX][EVT_MAX];

// Look up the table, call the handler, and return the next state
State dispatch(State current, const Event &ev);

// Handlers for each state
State wait_on_button_short(const Event &ev);
State wait_on_meas_start(const Event &ev);
State wait_on_get_info(const Event &ev);
State wait_on_get_latest(const Event &ev);
State wait_on_timer_100ms(const Event &ev);

State meas_on_button_long(const Event &ev);
State meas_on_meas_stop(const Event &ev);
State meas_on_get_info(const Event &ev);
State meas_on_get_latest(const Event &ev);
State meas_on_timer_100ms(const Event &ev);
State meas_on_timer_1s(const Event &ev);
State meas_on_disconnected(const Event &ev);

#endif // APP_HANDLER_H

4.2.1 Function pointers

typedef State (*EventHandler)(const Event &ev);

gives the name EventHandler to the pointer type for “a function that takes a const Event & and returns a State”. Function pointers let you choose the function to call at run time (by looking it up in a table).

4.2.2 The table itself and dispatch

#include "app_handler.h"

// State transition table
// Row = current state, column = event. Elements not written become nullptr (ignored).
// The [STATE_WAIT] = {...} syntax (designated array initializers) is a C feature;
// in C++ it is available as a GCC extension (list the elements in enum order).
const EventHandler handler_table[STATE_MAX][EVT_MAX] = {
    [STATE_WAIT] = {
        [EVT_NOP] = nullptr,
        [EVT_BUTTON_SHORT] = wait_on_button_short,
        [EVT_BUTTON_LONG] = nullptr,
        [EVT_TIMER_100MS] = wait_on_timer_100ms,
        [EVT_TIMER_1S] = nullptr,
        [EVT_BLE_CONNECTED] = nullptr,
        [EVT_BLE_DISCONNECTED] = nullptr,
        [EVT_BLE_CMD_GET_INFO] = wait_on_get_info,
        [EVT_BLE_CMD_MEAS_START] = wait_on_meas_start,
        [EVT_BLE_CMD_MEAS_STOP] = nullptr,
        [EVT_BLE_CMD_GET_LATEST] = wait_on_get_latest,
    },
    [STATE_MEAS] = {
        [EVT_NOP] = nullptr,
        [EVT_BUTTON_SHORT] = nullptr,
        [EVT_BUTTON_LONG] = meas_on_button_long,
        [EVT_TIMER_100MS] = meas_on_timer_100ms,
        [EVT_TIMER_1S] = meas_on_timer_1s,
        [EVT_BLE_CONNECTED] = nullptr,
        [EVT_BLE_DISCONNECTED] = meas_on_disconnected,
        [EVT_BLE_CMD_GET_INFO] = meas_on_get_info,
        [EVT_BLE_CMD_MEAS_START] = nullptr,
        [EVT_BLE_CMD_MEAS_STOP] = meas_on_meas_stop,
        [EVT_BLE_CMD_GET_LATEST] = meas_on_get_latest,
    },
};

State dispatch(State current, const Event &ev)
{
  // Guard: don't read outside the table for out-of-range states/events
  if (current >= STATE_MAX || ev.id >= EVT_MAX)
    return current;

  EventHandler h = handler_table[current][ev.id];
  if (h == nullptr)
    return current; // an event ignored in this state

  return h(ev);
}
  • The table is a two-dimensional array [STATE_MAX][EVT_MAX]. Rows are states, columns are events
  • dispatch() does a range check (guard) → looks up the table → ignores the event if it is nullptr → calls the handler and returns the next state
  • Handlers return the next state as the return value. The state is rewritten in only one place, loop(), so there is no need to hunt for “where did the state change?”
NoteDesignated initializers [STATE_WAIT] = {...}

Initializing array elements by specifying their indices is a C99 feature and is not in standard C++. GCC accepts it as an extension, but the elements must be listed in enum order (if you change the order you get the error sorry, unimplemented: non-trivial designated initializers not supported).

The advantage of this style is that you can read which handler sits in which cell. You can also list them without indices, but then if a column shifts when you add an event, you won’t notice.

4.3 Implementing the handlers

4.3.1 Idle state

#include "app_meas.h"
#include "app_handler.h"
#include "drv_imu.h"

// ===== Handlers for the idle state (STATE_WAIT) =====

State wait_on_button_short(const Event &ev)
{
  Serial.println("[WAIT] button short -> start measurement");
  meas_begin();
  return STATE_MEAS;
}

State wait_on_meas_start(const Event &ev)
{
  Serial.println("[WAIT] BLE cmd -> start measurement");
  meas_begin();
  return STATE_MEAS;
}

State wait_on_get_info(const Event &ev)
{
  reply_info();
  return STATE_WAIT;
}

State wait_on_get_latest(const Event &ev)
{
  reply_latest();
  return STATE_WAIT;
}

State wait_on_timer_100ms(const Event &ev)
{
  // keep only the latest value updated while idle (to answer GET_LATEST)
  g_latest_acc_mg = imu_read_magnitude_mg();
  return STATE_WAIT;
}

4.3.2 Measuring state

#include "app_meas.h"
#include "app_event.h"
#include "app_handler.h"
#include "drv_imu.h"

// ===== Handlers for the measuring state (STATE_MEAS) =====

State meas_on_button_long(const Event &ev)
{
  Serial.println("[MEAS] button long -> stop");
  return STATE_WAIT;
}

State meas_on_meas_stop(const Event &ev)
{
  Serial.println("[MEAS] BLE cmd -> stop");
  return STATE_WAIT;
}

State meas_on_get_info(const Event &ev)
{
  reply_info(); // processing shared with the idle state is gathered into a common function
  return STATE_MEAS;
}

State meas_on_get_latest(const Event &ev)
{
  reply_latest();
  return STATE_MEAS;
}

State meas_on_timer_100ms(const Event &ev)
{
  uint16_t v = imu_read_magnitude_mg();
  g_latest_acc_mg = v;
  meas_add_sample(v);
  return STATE_MEAS;
}

State meas_on_timer_1s(const Event &ev)
{
  MeasSummary s = meas_close_second();
  notify_summary(s);
  Serial.printf("[MEAS] seq=%u n=%u mean=%umg max=%umg dropped=%lu\n",
                s.seq, s.n, s.mean_mg, s.max_mg, (unsigned long)event_dropped_count());
  return STATE_MEAS;
}

State meas_on_disconnected(const Event &ev)
{
  // keep measuring even when disconnected (BLE is merely an outlet for the data)
  Serial.println("[MEAS] disconnected, keep measuring");
  return STATE_MEAS;
}

Rules for writing handlers:

  1. Finish quickly (no delay() or long loops)
  2. Return the next state. If the state does not change, return the current state
  3. Put shared processing into common functions (reply_info() etc.). Since there is a function per table cell, copy-paste tends to multiply if left alone

4.4 Adding a new state (exercise)

Let’s add a “calibration state”.

Specification:

  • A long press while idle enters the CALIB state
  • In the CALIB state, read acceleration every 100 ms and compute the average over 3 seconds (30 samples)
  • When 30 samples have accumulated, print the average to serial and return to WAIT
  • Button presses and BLE commands during CALIB are ignored (only GET_INFO is answered)

Steps:

  1. Add STATE_CALIB to enum State in app_state.h (before STATE_MAX)
  2. Write the state transition table on paper first (what to do on which event)
  3. Write handlers such as calib_on_timer_100ms
  4. Add a [STATE_CALIB] = {...} row to handler_table
  5. Set [EVT_BUTTON_LONG] in the [STATE_WAIT] row of handler_table to a handler that enters CALIB
  6. Add CALIB display to state_name() and to ui_update() in main.cpp (e.g. lighting red and green together gives yellow)
// app_handler_calib.cpp
#include "app_handler.h"
#include "app_meas.h"
#include "drv_imu.h"

static uint8_t s_count = 0;
static uint32_t s_sum = 0;

State wait_on_button_long(const Event &ev)
{
  s_count = 0;
  s_sum = 0;
  Serial.println("[WAIT] button long -> calibration");
  return STATE_CALIB;
}

State calib_on_timer_100ms(const Event &ev)
{
  s_sum += imu_read_magnitude_mg();
  if (++s_count < 30)
    return STATE_CALIB;
  Serial.printf("[CALIB] mean = %lu mg\n", (unsigned long)(s_sum / s_count));
  return STATE_WAIT;
}

State calib_on_get_info(const Event &ev)
{
  reply_info();
  return STATE_CALIB;
}

In the CALIB row of the table, set everything except EVT_TIMER_100MS and EVT_BLE_CMD_GET_INFO to nullptr. Confirm that the specification “ignore other events” is obvious at a glance on the table.

4.5 Processing on entering and leaving a state

If there is “processing that must always happen when entering a state” (an entry action), you tend to end up writing the same code in as many handlers as there are source states (in the sample, meas_begin() is called in two places).

As the scale grows, one approach is to detect the state change in loop() and call a table of entry functions.

typedef void (*StateAction)();
const StateAction on_enter[STATE_MAX] = {
    [STATE_WAIT] = nullptr,
    [STATE_MEAS] = meas_begin,
};

void loop()
{
  Event ev = event_wait();
  State next = dispatch(s_state, ev);
  if (next != s_state && on_enter[next] != nullptr)
    on_enter[next]();
  s_state = next;
  ui_update(s_state);
}