nRF52840 Event-Driven Firmware

Organizing buttons, timers, BLE and sensors with an event queue and a state transition table

Today’s goals

  1. Explain the limits of a super loop + flags
  2. Serialize interrupts, timers and BLE with an event queue
  3. Design and implement behaviour with a state transition table
  4. Respect the division of roles between ISRs, callbacks and handlers
  5. Operate the device from the browser with Web Bluetooth

1. Why event-driven?

Limits of the super loop

  • delay() or while waits stop everything
  • A single flag misses events
  • Races between callbacks and loop()
  • Combinations of flags explode
  • The CPU keeps spinning even with nothing to do

The big picture

flowchart LR
  BTN["Button ISR"] -->|post| Q[("Queue")]
  TMR["Timer"] -->|post| Q
  BLE["BLE"] -->|post| Q
  Q -->|wait| L["loop()"]
  L --> T["handler_table<br/>[state][event]"]
  T --> H["Handler → next state"]

  • Producers only push; the consumer (loop) processes one at a time
  • When the queue is empty, the CPU sleeps (tickless idle)

2. The event queue

Points

  • Event = ID + payload copied by value + timestamp
  • From an ISR xQueueSendToBackFromISR; from a task a non-waiting xQueueSendToBack
    • Decided via IPSR, unified in a single event_post()
  • Retrieval sleeps while waiting with portMAX_DELAY
  • When full, drop and count → monitor dropped

3. The state transition table

Design with a table

State BUTTON_SHORT BUTTON_LONG TIMER_100MS TIMER_1S CMD_START CMD_STOP
WAIT → MEAS — update latest — → MEAS —
MEAS — → WAIT sample aggregate & notify — → WAIT
  • “—” = nullptr = ignore. Gaps can be discussed before writing code

Implementation

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

const EventHandler handler_table[STATE_MAX][EVT_MAX] = {
    [STATE_WAIT] = { [EVT_BUTTON_SHORT] = wait_on_button_short, ... },
    [STATE_MEAS] = { [EVT_BUTTON_LONG]  = meas_on_button_long,  ... },
};

State dispatch(State cur, const Event &ev) {
  EventHandler h = handler_table[cur][ev.id];
  return h ? h(ev) : cur;
}
  • Handlers return the next state. The state is rewritten in one place in loop

4. Rules per event source

What to do where

Location Context What to do
Button attachInterrupt ISR Record time + post
SoftwareTimer Timer task post
Bluefruit callbacks BLE task Interpret + post
Handlers loop task Processing (I²C, sending, etc.)
  • ISR: delay / Serial / I²C forbidden; shared variables are volatile; debounce

5. BLE

GATT and protocol

  • One service + RX (Write) + TX (Notify)
  • Commands: 00 01 info / 01 00 start / 01 01 stop / 02 01 latest value
  • Responses: kind in the first 2 bytes; numbers are little-endian
  • Notify holds up to 20 bytes by default
  • The same command behaves differently depending on the state → the table decides

Web Bluetooth

  • Connect directly from the browser in Chrome / Edge
  • requestDevice({ filters: [{ services: [UUID] }] })
  • Serialize GATT operations (concurrent execution is an error)
  • The browser side is event-driven too

6. Pitfalls

Checklist

  • No delay() in handlers (compute the LED from millis())
  • Split long work (flash erase) or move it to another task
  • Don’t put pointers in the queue
  • Call event_init() first
  • Prefixes on header names (ble.h collides with SoftDevice)
  • Put common processing into functions, no copy-paste
  • Decouple app/ from hardware and test on the PC

Summary

  • Serialize occurrences of unknown timing with an event queue
  • List “in which state, when what happens, what to do” with a state transition table
  • ISRs and callbacks only post; processing happens in handlers
  • Design with a table → transcribe to the table → test cell by cell