10  Design tips and common pitfalls

An event-driven design with a state transition table prevents many problems on its own, but used wrongly it brings other problems. This chapter summarizes points you often run into in real projects.

10.1 1. Don’t wait inside handlers

delay(), flash erasing, long I²C transfers and the like inside a handler stop the processing of all events for that duration.

Symptom Example cause
Button responds slowly or misses presses Blinking the LED with delay() inside a handler
Measurement intervals become irregular Erasing a large region of external flash at once in the start-measurement handler
dropped increases The queue overflowed because of the above

Countermeasures:

  • Visual effects such as blinking are computed from millis() (Chapter 8)
  • Split time-consuming work. For example, erase flash one block at a time, advancing a little on each timer event (create a state for that)
  • Leave unavoidably long work to another task, and have it post a completion event when done

10.2 2. Interrupts and callbacks only post

Location Context it runs in What to do here
attachInterrupt callback ISR Record the time and post an event
SoftwareTimer callback Timer task Post an event
Bluefruit callbacks BLE task Interpret and post an event
Handlers loop task Do the processing here

Calling Serial.print() inside an ISR can hang. Emit debug output inside handlers, or in one place like the state transition log in main.cpp.

10.3 3. Put values in the queue, not pointers

// Dangerous: posting a pointer to the BLE buffer
event_post_ptr(EVT_BLE_CMD, data);  // data may become invalid once on_rx_write returns

By the time it is taken out of the queue, the original buffer may have been reused or freed. Copy the needed bytes into the payload. Arguments longer than the payload’s maximum length do not fit in the queue, so truncate the length in event_post() and set an upper limit in the protocol too.

10.4 4. Initialization order

Call event_init() (creating the queue) before any module that may post events. Callbacks may already be called right after BLE initialization or starting a timer.

10.5 5. Header name collisions

Common names such as ble.h, timer.h and event.h tend to collide with framework and library headers. -I in build_flags also affects library compilation, which leads to a hard-to-diagnose error in which #include "ble.h" inside a library reads your own header (Chapter 1). Use prefixes.

10.6 6. Don’t copy the same code per state

If you create a handler function per table cell, copy-paste like

State wait_on_get_latest(const Event &ev) { /* 30 lines of sending code */ return STATE_WAIT; }
State meas_on_get_latest(const Event &ev) { /* the same 30 lines */       return STATE_MEAS; }

tends to appear. Fixing only one of them causes bugs. Put the body of the processing into a common function (reply_latest()), and make the handlers only “call it and return the next state”.

For assembling transmit data too, rather than writing one byte at a time like val[6] = acc[0] >> 0; val[7] = acc[0] >> 8; …, using loops or small helper functions (e.g. put_u16le(buf, offset, value)) is more readable and less error-prone.

10.7 7. When the number of states grows

Scale Approach
2–5 states, 10–20 events The 2D table of this hands-on is sufficient
Many states, most cells nullptr Writing a switch (ev.id) per state, or a list of (state, event, handler)
Nesting, e.g. “measuring” inside “connected” Hierarchical state machine (a parent state handles common events)
Several independent behaviours (measurement, communication, power management) Have several state machines, or split into tasks

10.8 8. Testing on the PC

The code in app/ is written not to touch hardware directly (hardware is accessed through the functions in drivers/). Therefore, if you replace the drivers/ functions with fakes (stubs), you can test state transitions on the PC. PlatformIO has a mechanism to run unit tests on the PC with pio test -e native.

// What a test looks like
void test_long_press_stops_measurement() {
  Event ev = {};
  ev.id = EVT_BUTTON_LONG;
  TEST_ASSERT_EQUAL(STATE_WAIT, dispatch(STATE_MEAS, ev));
}
void test_long_press_is_ignored_while_waiting() {
  Event ev = {};
  ev.id = EVT_BUTTON_LONG;
  TEST_ASSERT_EQUAL(STATE_WAIT, dispatch(STATE_WAIT, ev));
}

Since a state transition table is a “table”, each cell of the table becomes a test case.

10.9 9. Memory and stack

  • The stack of the loop task in which loop() runs is 1024 words (4 KB) on this core. Taking a large array as a local variable inside a handler overflows the stack and leads to a hard-to-diagnose crash
  • Make large buffers static or put them in globals
  • Queue memory is sizeof(Event) × length. With a 64-byte payload and length 100, that alone is about 7 KB

10.10 Summary: checklist