flowchart LR
subgraph P["Producers (you never know when they fire)"]
ISR["Button interrupt"]
TM["Timer"]
BL["BLE"]
end
subgraph C["Consumer (processes one at a time, in order)"]
L["Main loop<br/>event_wait()"]
D["dispatch()<br/>state transition table"]
end
ISR -->|"just push"| Q[("Queue")]
TM -->|"just push"| Q
BL -->|"just push"| Q
Q --> L --> D
2 Why go event-driven?
2.1 The common way: a super loop + flags
The first thing you write in Arduino is a super loop like this.
bool measuring = false;
unsigned long last_sample = 0;
void loop() {
if (digitalRead(BUTTON) == LOW) { // when the button is pressed
delay(50); // meant as a debounce measure
if (!measuring) startMeas();
measuring = !measuring;
while (digitalRead(BUTTON) == LOW); // wait until released
}
if (measuring && millis() - last_sample >= 100) {
last_sample = millis();
readSensor();
}
if (bleCommandArrived) { // flag set by the BLE callback
bleCommandArrived = false;
handleCommand(bleCommandBuffer); // this also rewrites measuring...
}
updateLed();
}While it is small this is fine, but as you add features the following problems appear.
| Problem | Example |
|---|---|
| Waiting blocks everything | During delay(50) or the “wait until released” while, neither the sensor nor BLE commands are processed |
| Missed events | With a single flag, if two commands arrive before being processed, one of them is lost |
| Race conditions | loop() reads the buffer while the BLE callback (another task) is in the middle of rewriting it |
| Combinatorial explosion of states | measuring, connected, calibrating… as flags multiply, nobody can keep track of the combinations of ifs |
| No power saving | Even with nothing to do, loop() keeps spinning at full speed |
2.2 Event-driven + state transition table
So we divide the roles as follows.
- Producers only push “what happened” onto the queue. They do no heavy processing
- Only the consumer (the main loop) takes out events one at a time and processes them → processing is always serial, so no race conditions occur
- Which process to run is decided by a “current state × event” table → you can see at a glance “what to do when this event arrives in this state”
- When the queue is empty the main loop sleeps → the CPU can sleep, saving power
2.3 Designing state transitions with a table
Written as a state transition table, the behaviour of the sample firmware looks like this.
| State Event | BUTTON_SHORT | BUTTON_LONG | TIMER_100MS | TIMER_1S | BLE_CMD_MEAS_START | BLE_CMD_MEAS_STOP | BLE_CMD_GET_INFO / GET_LATEST | BLE_DISCONNECTED |
|---|---|---|---|---|---|---|---|---|
| WAIT | prepare measurement → MEAS | — | update latest value | — | prepare measurement → MEAS | — | send response | — |
| MEAS | — | → WAIT | add sample | aggregate and notify | — | → WAIT | send response | keep measuring |
“—” means ignore that event. Once it is a table, you can discuss gaps such as
- “What if MEAS_START arrives again while measuring?” → ignore
- “What if there is a long press while idle?” → ignore
before writing any code.
2.4 Simulator: running the state machine
The same state transition table as the sample firmware is reproduced here in JavaScript in the browser. Press the buttons to generate events and see how the state changes.
Current state
WAIT
LED
BLE
Disconnected
Queue
0 / 32
Generate events
Queue contents (head → tail)
State transition table (last looked-up cell highlighted)
Log
TipTry it
- Start a measurement with “Button short press” and stop it with “Button long press”. Check which cells of the table were looked up
- What happens if you press “Button long press” while idle? And if you send “CMD start meas.” while measuring?
- Turn on “Step mode”, press the buttons quickly several times, then keep pressing “Process one”. Confirm that events are processed one at a time, in the order they occurred
- What happens if you turn on “Run timers” while still in step mode and leave it? (Hint: the queue length is 32)
NoteExplanation
- In both cases the table cell is
nullptr, so nothing happens. With the flag approach, strange things tend to happen in such “unexpected combinations”. - Whatever the timing of interrupts or BLE, the main loop processes events one by one in order. The next event never cuts in while a handler is running (run-to-completion).
- If processing (consumption) stops while generation (production) continues, the queue soon fills up and subsequent events are discarded. On real hardware, the same thing happens when a handler blocks for a long time (Chapters 3 and 10).