3  The event queue

3.1 The event type

First, decide on a type that represents “what happened”.

#ifndef APP_EVENT_H
#define APP_EVENT_H

#include <Arduino.h>

#define EVENT_PAYLOAD_SIZE 16  // max payload length (large enough for BLE command arguments)
#define EVENT_QUEUE_LENGTH 32  // number of events the queue can hold

// Event IDs. These become the "columns" of the state transition table
enum EventId : uint8_t
{
  EVT_NOP,
  EVT_BUTTON_SHORT,       // button short press
  EVT_BUTTON_LONG,        // button long press (1 s or more)
  EVT_TIMER_100MS,        // 100 ms periodic timer
  EVT_TIMER_1S,           // 1 s periodic timer
  EVT_BLE_CONNECTED,      // BLE connected
  EVT_BLE_DISCONNECTED,   // BLE disconnected
  EVT_BLE_CMD_GET_INFO,   // command: get device info
  EVT_BLE_CMD_MEAS_START, // command: start measurement
  EVT_BLE_CMD_MEAS_STOP,  // command: stop measurement
  EVT_BLE_CMD_GET_LATEST, // command: get latest value
  EVT_MAX,
};

// Event put into the queue. The queue holds a copy of the value, so it must not contain pointers
struct Event
{
  EventId id;
  uint8_t length;                      // valid length of payload
  uint8_t payload[EVENT_PAYLOAD_SIZE]; // arguments (BLE command parameters etc.)
  uint32_t timestamp;                  // time of occurrence [ms]
};

void event_init();
// Can be called from any context (normal task or interrupt). Returns false if the queue is full
bool event_post(EventId id, const uint8_t *payload = nullptr, uint8_t length = 0);
// Blocks until an event arrives (the CPU can sleep meanwhile)
Event event_wait();
uint32_t event_dropped_count();
const char *event_name(EventId id);

#endif // APP_EVENT_H

Design points:

  • EventId is an enum. The trailing EVT_MAX becomes “the number of event kinds” and can be used as the number of columns of the state transition table
  • The payload (arguments) is held as an array. The queue copies the struct’s value, so if you put a pointer in it, by the time you take it out, what it points to may have been overwritten or may have disappeared
  • Keep the payload size to the necessary minimum. Queue memory = sizeof(Event) × queue length (in this sample about 24 bytes × 32 = about 0.8 KB)

3.2 FreeRTOS queues

A FreeRTOS queue is a mechanism for safely passing data between tasks, and between interrupts and tasks.

Function Purpose
xQueueCreate(length, item size) Create a queue
xQueueSendToBack(q, &item, wait time) Append to the back (from a task)
xQueueSendToBackFromISR(q, &item, &woken) Append to the back (from an interrupt handler)
xQueueReceive(q, &item, wait time) Take from the front
  • Adding to and taking from the queue is mutually exclusive, so it does not break even when called simultaneously from several tasks or interrupts
  • Items are passed by copy

3.3 Implementation

#include "app_event.h"
#include <FreeRTOS.h>
#include <queue.h>

static QueueHandle_t s_queue = nullptr;
static volatile uint32_t s_dropped = 0; // number of events dropped because the queue was full (also updated from interrupts)

void event_init()
{
  if (s_queue == nullptr)
  {
    s_queue = xQueueCreate(EVENT_QUEUE_LENGTH, sizeof(Event));
  }
}

static inline bool in_isr()
{
  // if IPSR is non-zero we are inside an interrupt handler
  return __get_IPSR() != 0;
}

bool event_post(EventId id, const uint8_t *payload, uint8_t length)
{
  if (s_queue == nullptr)
    return false;

  Event ev = {};
  ev.id = id;
  ev.length = min<uint8_t>(length, EVENT_PAYLOAD_SIZE);
  if (payload != nullptr && ev.length > 0)
  {
    memcpy(ev.payload, payload, ev.length);
  }
  ev.timestamp = millis();

  BaseType_t ok;
  if (in_isr())
  {
    BaseType_t woken = pdFALSE;
    ok = xQueueSendToBackFromISR(s_queue, &ev, &woken);
    portYIELD_FROM_ISR(woken);
  }
  else
  {
    // don't wait: so as not to stall the BLE or timer tasks. If full, drop and count
    ok = xQueueSendToBack(s_queue, &ev, 0);
  }
  if (ok != pdTRUE)
  {
    s_dropped++;
    return false;
  }
  return true;
}

Event event_wait()
{
  Event ev;
  if (xQueueReceive(s_queue, &ev, portMAX_DELAY) == pdTRUE)
  {
    return ev;
  }
  Event nop = {};
  nop.id = EVT_NOP;
  return nop;
}

uint32_t event_dropped_count()
{
  return s_dropped;
}

const char *event_name(EventId id)
{
  switch (id)
  {
  case EVT_NOP: return "NOP";
  case EVT_BUTTON_SHORT: return "BUTTON_SHORT";
  case EVT_BUTTON_LONG: return "BUTTON_LONG";
  case EVT_TIMER_100MS: return "TIMER_100MS";
  case EVT_TIMER_1S: return "TIMER_1S";
  case EVT_BLE_CONNECTED: return "BLE_CONNECTED";
  case EVT_BLE_DISCONNECTED: return "BLE_DISCONNECTED";
  case EVT_BLE_CMD_GET_INFO: return "BLE_CMD_GET_INFO";
  case EVT_BLE_CMD_MEAS_START: return "BLE_CMD_MEAS_START";
  case EVT_BLE_CMD_MEAS_STOP: return "BLE_CMD_MEAS_STOP";
  case EVT_BLE_CMD_GET_LATEST: return "BLE_CMD_GET_LATEST";
  default: return "UNKNOWN";
  }
}

3.3.1 Inside an interrupt, or inside a task?

The FreeRTOS API has ...FromISR versions that may be called from an interrupt handler (ISR) and normal versions to be called from tasks. Calling a normal version from an ISR means “waiting” inside the ISR, which breaks the system.

event_post() looks at the Cortex-M IPSR register (the number of the exception currently executing) and uses

  • a normal task if it is 0 → xQueueSendToBack
  • an interrupt handler if it is non-zero → xQueueSendToBackFromISR

accordingly. This way the callers (button, timer, BLE) can call event_post() without caring which context they are running in.

NoteportYIELD_FROM_ISR

If, as a result of pushing onto the queue inside an ISR, a higher-priority task (one that was waiting for events) becomes able to run, woken becomes pdTRUE. portYIELD_FROM_ISR(woken) requests a switch to that task immediately after leaving the ISR.

3.3.2 Non-waiting posting, and recording drops

When posting from a task, the wait time is set to 0 (do not wait).

  • With portMAX_DELAY (wait forever), the calling task stops when the queue is full. BLE callbacks run in the BLE stack’s task and timer callbacks in the timer task, so if those stop, even BLE communication and other timers stop
  • Instead, events that could not be posted because the queue was full are discarded and counted (event_dropped_count()). The count is shown in the log during measurement, so you can check whether drops occurred

The queue fills up when handler processing is too slow (consumption cannot keep up with the rate at which events are generated). Making the queue longer is only treating the symptom; the root fix is to make the handlers shorter (Chapter 10).

3.3.3 Waiting retrieval and power saving

xQueueReceive(s_queue, &ev, portMAX_DELAY);

The retrieving side waits forever. While the queue is empty, the loop task is in the blocked state, and if no other task is runnable FreeRTOS enters idle. The FreeRTOS of the Adafruit nRF52 core has tickless idle enabled (configUSE_TICKLESS_IDLE = 1), so the CPU sleeps until the next event (timer expiry or interrupt).

Because loop() no longer spins idly, just going event-driven lowers power consumption.

3.4 The main loop

#include <Arduino.h>
#include "app_event.h"
#include "app_handler.h"
#include "app_meas.h"
#include "app_state.h"
#include "drv_ble.h"
#include "drv_button.h"
#include "drv_imu.h"
#include "drv_led.h"
#include "drv_timer.h"

static State s_state = STATE_WAIT;

// LED display according to the state. Called every time one event is processed
// (because of the 100 ms timer, it is updated at least at 10 Hz)
static void ui_update(State state)
{
  switch (state)
  {
  case STATE_WAIT:
    if (ble_is_connected())
      led_blink(LED_COLOR_BLUE, 100, 1000);
    else
      led_blink(LED_COLOR_GREEN, 100, 2000);
    break;
  case STATE_MEAS:
    led_blink(LED_COLOR_RED, 100, 500);
    break;
  default:
    led_set(LED_COLOR_OFF);
    break;
  }
}

void setup()
{
  Serial.begin(115200);
  event_init(); // create it before other modules post events
  led_init();
  imu_init();
  button_init();
  ble_init();
  timer_init();
  Serial.println("boot: state=WAIT");
}

void loop()
{
  // 1. Wait for an event (this task sleeps until one arrives, and the CPU can sleep)
  Event ev = event_wait();

  // 2. Pick and run the handler via the state transition table, and receive the next state
  State next = dispatch(s_state, ev);

  // 3. Log if the state changed (timer events are frequent, so they are not logged)
  if (next != s_state)
  {
    Serial.printf("%s --[%s]--> %s\n", state_name(s_state), event_name(ev.id), state_name(next));
  }
  s_state = next;

  // 4. Update the display
  ui_update(s_state);
}

loop() is a function that is called repeatedly inside FreeRTOS’s loop task. In one call it

  1. waits for and takes out one event
  2. processes it with the state transition table (Chapter 4)
  3. logs if the state changed
  4. updates the LED
ImportantKey points
  • Put events into the queue as copied values. Do not put pointers in
  • From an ISR use the FromISR version; from a task post without waiting
  • Retrieval waits forever → when empty, the CPU sleeps
  • If consumption cannot keep up with production the queue overflows → keep handlers short