knaxuslearn · build · ship

Projects / Data logger / Phase 3

Phase 3 of 4 · about 2.5 hours

Sample on time, whatever else is going on

You end with readings taken inside an interrupt and queued for the main loop, a console that answers status, dump, rate and live, and a test that makes the logger drop readings on purpose and counts every one it lost.

In Phase 2 the main loop takes the reading. That works until the loop has something slow to do. Printing a long dump at 115200 baud takes about 3 seconds per 1000 lines, and erasing flash on this chip takes a large fraction of a second. While the loop is busy, nobody takes readings, and the gap never shows in the output. A logger that silently skips readings is worse than one that stops.

The fix is to split the work. The SysTick interrupt takes each reading on time, however busy the main loop is, and puts it in a queue. The main loop takes readings out of the queue when it can. If the queue fills up, the interrupt counts what it had to throw away, so the loss is visible.

The interrupt samples on time. The main loop catches up when it can.

Step 3.1: A queue with no locks (about 35 minutes)

A ring buffer is a fixed array used in a circle. One side adds at the head, the other removes at the tail. Ours has exactly one writer, the interrupt, and one reader, the main loop. If only the interrupt writes head and only the main loop writes tail, neither ever needs to stop the other, which means no locks.

One writer moves the head. One reader moves the tail. No locks.

Readings need a type. Create sample.h:

#ifndef SAMPLE_H
#define SAMPLE_H

#include <stdint.h>

/* One reading. seq counts every reading taken, so a gap in seq means one was lost. */
typedef struct {
    uint32_t seq;
    uint32_t ms;
    int32_t centi;
} sample_t;

#endif

Create ring.h:

/*
 * A queue of samples from one interrupt handler to the main loop.
 * Only the handler writes head and only the main loop writes tail, so no locks are needed.
 */
#ifndef RING_H
#define RING_H

#include <stdbool.h>
#include <stdint.h>

#include "sample.h"

#define RING_SIZE 64u /* a power of two, so head % RING_SIZE stays right when head wraps */

typedef struct {
    volatile uint32_t head; /* total samples ever pushed */
    volatile uint32_t tail; /* total samples ever popped */
    sample_t items[RING_SIZE];
} ring_t;

static inline bool ring_push(ring_t *r, const sample_t *s)
{
    uint32_t head = r->head;
    if (head - r->tail == RING_SIZE)
        return false; /* full */
    r->items[head % RING_SIZE] = *s;
    __atomic_signal_fence(__ATOMIC_SEQ_CST); /* store the item before publishing it */
    r->head = head + 1;
    return true;
}

static inline bool ring_pop(ring_t *r, sample_t *out)
{
    uint32_t tail = r->tail;
    if (r->head == tail)
        return false; /* empty */
    __atomic_signal_fence(__ATOMIC_SEQ_CST); /* read head before reading the item */
    *out = r->items[tail % RING_SIZE];
    __atomic_signal_fence(__ATOMIC_SEQ_CST); /* finish reading before freeing the slot */
    r->tail = tail + 1;
    return true;
}

#endif

head and tail count every item ever pushed and popped, and never reset. The number of items in the queue is head - tail, and the slot for an item is the count modulo the size. With unsigned numbers this stays right even when the counts wrap past 4 billion, as long as the size is a power of two.

The order of the writes matters. ring_push stores the item first and only then moves head, so the main loop can never see a new head before the item is in place. __atomic_signal_fence stops the compiler from swapping those two writes. On a single-core Cortex-M4 that is all we need, because the core itself does not reorder memory accesses in a way an interrupt on the same core could see.

Test it on your laptop. Create tests/test_ring.c:

#include <stdio.h>
#include "../ring.h"

static int failures;

#define CHECK(cond)                                         \
    do {                                                    \
        if (!(cond)) {                                      \
            printf("FAIL line %d: %s\n", __LINE__, #cond);  \
            failures++;                                     \
        }                                                   \
    } while (0)

int main(void)
{
    static ring_t r;
    sample_t s = {0}, out;

    CHECK(!ring_pop(&r, &out)); /* starts empty */

    for (uint32_t i = 0; i < RING_SIZE; i++) {
        s.seq = i;
        CHECK(ring_push(&r, &s));
    }
    s.seq = 999;
    CHECK(!ring_push(&r, &s)); /* the 65th does not fit */

    for (uint32_t i = 0; i < RING_SIZE; i++)
        CHECK(ring_pop(&r, &out) && out.seq == i); /* first in, first out */
    CHECK(!ring_pop(&r, &out));

    /* Start the counters just below 2^32 and push past the wrap. */
    r.head = r.tail = 0xFFFFFFF0u;
    for (uint32_t i = 0; i < 40; i++) {
        s.seq = i;
        CHECK(ring_push(&r, &s));
        CHECK(ring_pop(&r, &out) && out.seq == i);
    }

    printf("%s\n", failures ? "ring: FAILED" : "ring: all passed");
    return failures != 0;
}

The last loop starts the counters 16 short of the 32-bit limit and runs past it, which is the case that breaks a ring buffer written with head == RING_SIZE checks. Add it to the Makefile's test target:

	gcc -std=c11 -Wall -Wextra -o build/host/test_ring tests/test_ring.c

Add test_ring to TESTS, then:

make test
fmt: all passed
temp: all passed
ring: all passed

Step 3.2: Take readings in the interrupt (about 30 minutes)

Create sampler.h:

#ifndef SAMPLER_H
#define SAMPLER_H

#include <stdbool.h>
#include <stdint.h>

#include "sample.h"

void sampler_tick(uint32_t now); /* called from SysTick_Handler once a millisecond */
bool sampler_next(sample_t *out);
void sampler_set_rate(uint32_t ms);
uint32_t sampler_rate(void);
uint32_t sampler_taken(void);
uint32_t sampler_dropped(void);

#endif

And sampler.c:

/* Take a reading every rate_ms milliseconds, inside the SysTick interrupt. */
#include "adc.h"
#include "board.h"
#include "ring.h"
#include "sampler.h"
#include "temp.h"

static ring_t queue;
static volatile uint32_t rate_ms = 1000;
static volatile uint32_t taken;   /* written only by the interrupt */
static volatile uint32_t dropped; /* written only by the interrupt */
static uint32_t elapsed;          /* used only by the interrupt */

void sampler_tick(uint32_t now)
{
    if (++elapsed < rate_ms)
        return;
    elapsed = 0;

    uint32_t raw = adc_read();
    sample_t s = {.seq = taken, .ms = now, .centi = temp_centi(raw, TS_CAL30, TS_CAL110)};
    taken = taken + 1;
    if (!ring_push(&queue, &s))
        dropped = dropped + 1;
}

bool sampler_next(sample_t *out)
{
    return ring_pop(&queue, out);
}

void sampler_set_rate(uint32_t ms)
{
    rate_ms = ms;
}

uint32_t sampler_rate(void)
{
    return rate_ms;
}

uint32_t sampler_taken(void)
{
    return taken;
}

uint32_t sampler_dropped(void)
{
    return dropped;
}

Every reading gets a sequence number from taken, whether or not it fits in the queue. A gap in the numbers is a reading that was lost. rate_ms is volatile because the main loop changes it and the interrupt reads it.

Is it safe to read the ADC inside an interrupt? On the board one conversion takes about 60 microseconds, and the interrupt comes once a millisecond, so even at the fastest rate the console allows, one reading every 10 ms, it uses well under 1% of the time. Keep interrupt handlers short and predictable, and this one is.

Have SysTick call the sampler. In ticks.c, include sampler.h and change the handler:

void SysTick_Handler(void)
{
    ms_count++;
    sampler_tick(ms_count);
}

Step 3.3: Receive by interrupt (about 30 minutes)

So far we only send. To take commands, the USART must receive, and a character can arrive at any moment, even while the main loop is busy. If we do not read it before the next one arrives, it is lost. So reception is done by interrupt too, into a small buffer, using the same one-writer, one-reader idea as the ring.

The USART's interrupt number differs between the two chips' serial ports: 37 for USART1 and 38 for USART2. Add it to board.h, next to UART_BASE, in the QEMU part:

#define UART_IRQ  37          /* USART1 interrupt number */

And in the Nucleo part:

#define UART_IRQ  38          /* USART2 interrupt number */

In startup.c, include board.h at the top, add the alias, and put the entry in the table. The chip's own interrupts start at entry 16:

void UART_IRQHandler(void) __attribute__((weak, alias("Default_Handler")));
    [16 + UART_IRQ] = UART_IRQHandler, /* chip interrupts start at entry 16 */

Replace uart.h:

#ifndef UART_H
#define UART_H

#include <stdint.h>

void uart_init(void);
void uart_putc(char c);
void uart_puts(const char *s);
void uart_put_u32(uint32_t value);
void uart_put_centi(int32_t hundredths);
int uart_getc(void); /* the next received character, or -1 if there is none */

#endif

And uart.c:

/* The serial port: send by waiting, receive by interrupt. */
#include "board.h"
#include "fmt.h"
#include "uart.h"

#define USART_SR  REG32(UART_BASE + 0x00)
#define USART_DR  REG32(UART_BASE + 0x04)
#define USART_BRR REG32(UART_BASE + 0x08)
#define USART_CR1 REG32(UART_BASE + 0x0C)

#define SR_ORE    (1u << 3)  /* a character arrived before we read the last one */
#define SR_RXNE   (1u << 5)  /* a received character is waiting */
#define SR_TXE    (1u << 7)  /* the data register is free for the next character */
#define CR1_UE    (1u << 13) /* USART on */
#define CR1_RXNEIE (1u << 5) /* interrupt when a character arrives */
#define CR1_TE    (1u << 3)  /* transmitter on */
#define CR1_RE    (1u << 2)  /* receiver on */

#define NVIC_ISER(n) REG32(0xE000E100u + 4u * (n))

#define RX_SIZE 64u
static volatile char rx_buf[RX_SIZE];
static volatile uint32_t rx_head, rx_tail;

void UART_IRQHandler(void)
{
    uint32_t sr = USART_SR;
    if (sr & (SR_RXNE | SR_ORE)) {
        char c = (char)USART_DR; /* reading DR clears both flags */
        if (rx_head - rx_tail < RX_SIZE) {
            rx_buf[rx_head % RX_SIZE] = c;
            rx_head = rx_head + 1;
        }
    }
}

void uart_init(void)
{
    USART_BRR = (CPU_HZ + 115200 / 2) / 115200; /* 115200 baud */
    USART_CR1 = CR1_UE | CR1_TE | CR1_RE | CR1_RXNEIE;
    NVIC_ISER(UART_IRQ / 32) = 1u << (UART_IRQ % 32);
}

int uart_getc(void)
{
    if (rx_head == rx_tail)
        return -1;
    char c = rx_buf[rx_tail % RX_SIZE];
    rx_tail = rx_tail + 1;
    return (unsigned char)c;
}

void uart_putc(char c)
{
    if (c == '\n')
        uart_putc('\r');
    while (!(USART_SR & SR_TXE)) {
    }
    USART_DR = (uint32_t)c;
}

void uart_puts(const char *s)
{
    while (*s)
        uart_putc(*s++);
}

void uart_put_u32(uint32_t value)
{
    char buf[12];
    fmt_u32(buf, value);
    uart_puts(buf);
}

void uart_put_centi(int32_t hundredths)
{
    char buf[16];
    fmt_centi(buf, hundredths);
    uart_puts(buf);
}

Three things switch reception on: CR1_RE turns on the receiver, CR1_RXNEIE asks for an interrupt when a character arrives, and the write to NVIC_ISER lets that interrupt reach the core. The NVIC is the core's interrupt controller, and every chip interrupt is off there until you enable it.

The handler also checks SR_ORE, the overrun flag, which means a character arrived before we read the previous one. If you leave it set, the interrupt fires again and again forever, and the main loop never runs again. Reading DR clears it.

uart_put_u32 and uart_put_centi save the two lines of fmt code we kept repeating.

Step 3.4: A console (about 25 minutes)

The main loop now needs somewhere to keep readings and a way to show them. For this phase, keep the last 128 in RAM. We swap this for flash in Phase 4 and keep the same idea. Create log.h:

/* Where readings are kept. Phase 3 keeps them in RAM. */
#ifndef LOG_H
#define LOG_H

#include <stdbool.h>
#include <stdint.h>

#include "sample.h"

void log_add(const sample_t *s);
uint32_t log_count(void);
bool log_get(uint32_t index, sample_t *out); /* 0 is the oldest kept */

#endif

And log.c:

/* The last LOG_SIZE readings, in RAM. A reset loses them all. */
#include "log.h"

#define LOG_SIZE 128u

static sample_t kept[LOG_SIZE];
static uint32_t added;

void log_add(const sample_t *s)
{
    kept[added % LOG_SIZE] = *s;
    added++;
}

uint32_t log_count(void)
{
    return added < LOG_SIZE ? added : LOG_SIZE;
}

bool log_get(uint32_t index, sample_t *out)
{
    if (index >= log_count())
        return false;
    uint32_t oldest = added - log_count();
    *out = kept[(oldest + index) % LOG_SIZE];
    return true;
}

Now the console. It collects typed characters into a line, echoes them so you can see what you type, and runs the line when you press Enter. Create console.h:

#ifndef CONSOLE_H
#define CONSOLE_H

#include <stdbool.h>

#include "sample.h"

void console_feed(char c);
bool console_live(void);
void console_print_sample(const sample_t *s);

#endif

And console.c:

/* Read a line from the serial port and run it as a command. */
#include <stdint.h>

#include "console.h"
#include "log.h"
#include "sampler.h"
#include "ticks.h"
#include "uart.h"

#define LINE_MAX 32

static char line[LINE_MAX];
static uint32_t line_len;
static bool live;

static bool word_is(const char *s, const char *word)
{
    while (*word && *s == *word) {
        s++;
        word++;
    }
    return *word == '\0' && (*s == '\0' || *s == ' ');
}

/* Read the number after the first space. Returns false if there is none. */
static bool number_arg(const char *s, uint32_t *out)
{
    while (*s && *s != ' ')
        s++;
    while (*s == ' ')
        s++;
    if (*s < '0' || *s > '9')
        return false;
    uint32_t value = 0;
    while (*s >= '0' && *s <= '9') {
        if (value > 100000000u)
            return false; /* far too big, and close to overflowing */
        value = value * 10 + (uint32_t)(*s++ - '0');
    }
    *out = value;
    return *s == '\0';
}

void console_print_sample(const sample_t *s)
{
    uart_puts("#");
    uart_put_u32(s->seq);
    uart_puts(" t=");
    uart_put_u32(s->ms);
    uart_puts(" ms temp=");
    uart_put_centi(s->centi);
    uart_puts(" C\n");
}

static void show_status(void)
{
    uart_puts("uptime ");
    uart_put_u32(ticks_ms());
    uart_puts(" ms, rate ");
    uart_put_u32(sampler_rate());
    uart_puts(" ms, taken ");
    uart_put_u32(sampler_taken());
    uart_puts(", kept ");
    uart_put_u32(log_count());
    uart_puts(", dropped ");
    uart_put_u32(sampler_dropped());
    uart_puts("\n");
}

static void dump(void)
{
    sample_t s;
    for (uint32_t i = 0; log_get(i, &s); i++)
        console_print_sample(&s);
}

static void run(const char *cmd)
{
    uint32_t n;
    if (cmd[0] == '\0') {
        return;
    } else if (word_is(cmd, "status")) {
        show_status();
    } else if (word_is(cmd, "dump")) {
        dump();
    } else if (word_is(cmd, "live")) {
        live = !live;
        uart_puts(live ? "live on\n" : "live off\n");
    } else if (word_is(cmd, "rate") && number_arg(cmd, &n) && n >= 10 && n <= 60000) {
        sampler_set_rate(n);
        uart_puts("ok\n");
    } else if (word_is(cmd, "busy") && number_arg(cmd, &n) && n <= 10000) {
        ticks_delay(n); /* pretend the main loop is stuck on slow work */
        uart_puts("ok\n");
    } else {
        uart_puts("commands: status, dump, live, rate <10-60000 ms>, busy <ms>\n");
    }
}

void console_feed(char c)
{
    if (c == '\r' || c == '\n') {
        uart_puts("\n");
        line[line_len] = '\0';
        run(line);
        line_len = 0;
        uart_puts("> ");
    } else if ((c == '\b' || c == 0x7f) && line_len > 0) {
        line_len--;
        uart_puts("\b \b");
    } else if (c >= ' ' && c <= '~' && line_len < LINE_MAX - 1) {
        line[line_len++] = c;
        uart_putc(c); /* echo, so you can see what you type */
    }
}

bool console_live(void)
{
    return live;
}

There is no strcmp or atoi without a C library, so word_is and number_arg do the little we need. number_arg refuses numbers big enough to overflow. busy is there for testing: it stalls the main loop for as long as you ask, the way a slow flash erase would.

Replace main.c:

#include "adc.h"
#include "board.h"
#include "console.h"
#include "log.h"
#include "sampler.h"
#include "ticks.h"
#include "uart.h"

int main(void)
{
    board_init();
    uart_init();
    ticks_init();
    adc_init();
    uart_puts("logger: booted\n> ");

    for (;;) {
        sample_t s;
        while (sampler_next(&s)) {
            log_add(&s);
            if (console_live())
                console_print_sample(&s);
            led_toggle();
        }

        /* One character per pass, so samples are saved between commands. */
        int c = uart_getc();
        if (c >= 0)
            console_feed((char)c);
        else
            __asm volatile("wfi"); /* nothing to do: sleep until the next interrupt */
    }
}

The loop does one character of console input per pass, so readings get saved between commands even when you paste several at once. When there is nothing to do, wfi (wait for interrupt) puts the core to sleep until the next interrupt, at most a millisecond away. On a battery-powered logger, that sleep is most of the battery saving.

Update the source list in the Makefile:

SRC = startup.c board.c uart.c ticks.c adc.c fmt.c temp.c sampler.c log.c console.c main.c
make run

Type status, dump and help after a few seconds:

logger: booted
> status
uptime 3126 ms, rate 1000 ms, taken 3, kept 3, dropped 0
> dump
#0 t=1000 ms temp=-277.09 C
#1 t=2000 ms temp=-274.83 C
#2 t=3000 ms temp=-272.58 C
> help
commands: status, dump, live, rate <10-60000 ms>, busy <ms>

Your uptime will differ, since it depends on how fast you type. Try live to watch readings arrive and live again to stop.

Step 3.5: Make it drop readings on purpose (about 30 minutes)

A queue only helps if it is big enough. This one holds 64 readings. At one reading every 10 ms, that covers 640 ms of a busy main loop. So a 500 ms stall should lose nothing, and a 1000 ms stall should lose about 1000 / 10 − 64 = 36 readings. Test the prediction:

> rate 10
ok
> status
uptime 759 ms, rate 10 ms, taken 50, kept 50, dropped 0
> busy 500
ok
> status
uptime 1360 ms, rate 10 ms, taken 110, kept 110, dropped 0
> busy 1000
ok
> status
uptime 2360 ms, rate 10 ms, taken 210, kept 128, dropped 36

Exactly 36 dropped. kept stops at 128 because the RAM log keeps only the last 128. Type dump and look for the gap in the sequence numbers where the readings were dropped.

This is how to size a queue: find the longest time the main loop can be busy, divide by the time between readings, and add a margin. Then count drops in the field anyway, because you will have missed a case.

On the board: the same test works. You can also see something QEMU cannot show you: with live on and rate 10, each printed line takes about 3 ms at 115200 baud, so printing keeps up. Make the lines longer or the rate faster and the serial port becomes the slow part, and dropped starts to climb.

Phase 3 done

Readings now arrive on time whatever the main loop is doing, the loop sleeps when it has nothing to do, and when readings are lost you know exactly how many. But a reset still wipes everything.