---
title: "Embedded lab: a data logger"
heading: Sampling, statistics and reports, all in C
eyebrow: C12 · Lesson 52 · Embedded lab
xp: 50
---

::: hook
A data logger is a small embedded system with every part this course has covered: a timer interrupt sampling a sensor at a steady rate, fixed-point conversion to real units, a ring buffer holding the recent readings, statistics computed without floating point, a text report over the UART, and sleep between samples to save the battery. This lab builds one in C, a part at a time, and the play shows the finished logger running.
:::

::: play
- The logger samples a thermistor 10 times a second from a timer interrupt, converts each reading to tenths of a degree with the lesson 18 table, and keeps the last second's in a ring buffer.
- Every second the main loop reports the average, minimum and maximum over the UART, then sleeps. The room warms 2 °C a second, so the reports climb: 21.1, 23.1, 25.1 °C on average.
- The power panel shows about 0.55 mA: asleep nearly all the time. The program is about 1.2 KB.
:::
:::

```sim board
lang: c
attach: thermistor ADC1 | temp 20 + 2*t
attach: terminal
scope: TX
run: 3.2 s
show: power, debug
battery: 220 mAh
code:
#include "board.h"

// ADC codes at 0, 10, ... 80 °C for the thermistor divider (lesson 18)
const uint16_t table[9] = {939, 1357, 1817, 2270, 2676, 3014, 3280, 3482, 3633};

int tenths(int code) {
    if (code <= table[0]) return 0;
    for (int i = 0; i < 8; i++)
        if (code <= table[i + 1])
            return i * 100 + (code - table[i]) * 100 / (table[i + 1] - table[i]);
    return 800;
}

#define N 10                          // one second of samples
volatile int16_t ring[N];
volatile uint32_t count = 0;

void __attribute__((interrupt)) on_timer(void) {   // 10 times a second
    TIMER_FLAGS = 1;
    ADC_CTRL = 1 | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    ring[count % N] = tenths(ADC_DATA);
    count++;
}

void putc(char c) { while (UART_STATUS & UART_TX_FULL) ; UART_DATA = c; }
void puts(const char *s) { while (*s) putc(*s++); }
void put_tenths(int v) {              // 235 -> "23.5"
    if (v < 0) { putc('-'); v = -v; }
    char d[6]; int k = 0;
    int whole = v / 10;
    do { d[k++] = '0' + whole % 10; whole /= 10; } while (whole);
    while (k) putc(d[--k]);
    putc('.');
    putc('0' + v % 10);
}

void report(void) {
    int lo = ring[0], hi = ring[0], sum = 0;
    for (int i = 0; i < N; i++) {
        int v = ring[i];
        if (v < lo) lo = v;
        if (v > hi) hi = v;
        sum += v;
    }
    puts("avg "); put_tenths((sum + N / 2) / N);
    puts(" min "); put_tenths(lo);
    puts(" max "); put_tenths(hi);
    putc('\n');
}

int main(void) {
    UART_BAUDDIV = 87;
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;                   // every 100 ms
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    uint32_t reported = 0;
    while (1) {
        if (count >= reported + N) {  // another full second of samples
            reported += N;
            report();
        }
        __wfi();
    }
}
```

::: predict
## The ISR runs 10 times a second and takes about 400 cycles (the conversion's 10 µs wait plus the table lookup). What share of the processor does it use?

- [ ] 4%
- [ ] 0.4%
- [x] 0.04%
- [ ] 40%

::: reveal
0.04%: $400 \times 10 = 4000$ cycles a second out of $10^7$. Even the reports, about 30 characters a second at 87 µs each, keep the processor busy for only 2.6 ms a second, mostly waiting on the UART: the logger could sample far faster before time ran short.
:::
:::

::: nameit
## The parts

| Part | Lesson |
|---|---|
| a timer interrupt at a fixed rate | 9, 10 |
| the ADC and the thermistor table | 12, 13 |
| a ring buffer of recent readings | 20 |
| integer statistics: min, max, rounded average | 4, 13 |
| formatting numbers as text for the UART | 19 |
| sleeping between samples | 29 |

## Integer statistics

For readings in tenths of a degree, the average rounded to the nearest tenth is `(sum + N/2) / N`, with the sum in a type wide enough for N readings. Min and max start at the first reading (never at 0, which may be lower than every reading).

## Formatting tenths

Split v into its whole part `v / 10` and its tenth `v % 10`, print the whole part's digits (most significant first, from a reversed `% 10` loop), then a point and the tenth. Handle the sign first, since `%` of a negative number is negative in C.

## Sharing data with the ISR

The ISR writes `ring` and `count`; the report reads them. A report taken while a sample is half-written could mix old and new values; this logger reports right after a sample and long before the next, so it's safe, but a faster logger would copy the buffer with interrupts disabled for those few instructions.
:::

::: example
## How much RAM does a ring buffer of one minute's readings take at 10 Hz, stored as 16-bit tenths?

::: solution
1. **Count the readings.** One minute at 10 Hz is 600 readings.
2. **Multiply by their size.**
   $$600 \times 2\ \text{bytes} = 1200\ \text{bytes}$$
   about 2% of this board's 60 KiB.

**Answer:** 1200 bytes, about 2% of the board's RAM.
:::
:::

::: example
## Readings (tenths) are 231, 228, 240 and 236. What do min, max and the rounded average come to?

::: solution
1. **Min and max.** Min 228, max 240.
2. **Sum.** The sum is 935.
3. **Rounded average.** Adding half the divisor first makes the integer division round:
   $$\frac{935 + 2}{4} = 234$$
   (234.25 rounds to 234).
4. **Format the report.** In degrees, it reads `avg 23.4 min 22.8 max 24.0`.

**Answer:** min 228, max 240 and average 234, so the report reads `avg 23.4 min 22.8 max 24.0`.
:::
:::

::: check
given: f = 10 | 100 | 1000; c = 400 | 1500
answer: 100*f*c/1e7
unit: %
tolerance: 0.5%

## A sampling ISR of {c} cycles runs {f} times a second. What share of the processor does it use?

::: right
Right. {answer}%.
:::

::: misses
- [any] Not yet. Cycles per second over 10 MHz.
:::
:::

::: check
given: f = 1 | 10 | 50; s = 10 | 60; b = 2 | 4
answer: f*s*b
unit: bytes
tolerance: 0

## A logger keeps {s} s of readings at {f} Hz, {b} bytes each. How much RAM does its buffer need?

::: right
Right. {answer} bytes.
:::

::: misses
- [any] Not yet. Readings times bytes each.
:::
:::

::: check
given: n = 20 | 32 | 50; b = 9600 | 115200
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

## A report line is {n} characters at {b} baud. How long does it take to send?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. 10 bits per character.
:::
:::

::: check
given: s = 935 | 1007 | 2335; N = 4 | 10
answer: floor((s + floor(N/2))/N)
tolerance: 0

## N = {N} readings in tenths sum to {s}. What does `(sum + N/2) / N` give, in integer arithmetic?

::: right
Right. {answer} tenths.
:::

::: misses
- [floor(s/N)] That truncates; adding N/2 first rounds.
- [any] Not yet. Add half of N, then divide.
:::
:::

::: check
given: I = 0.55 | 2.05; Q = 220 | 1000
answer: Q/I/24
unit: days
tolerance: 0.5%

## The logger averages {I} mA from a {Q} mAh battery. How many days does it run?

::: right
Right. {answer} days.
:::

::: misses
- [any] Not yet. Capacity over current, then hours to days.
:::
:::

::: check
kind: c
attach: pot ADC0 = 1.2 V
run: 2
expect: period(P0) = 200 ms ± 0.2%; current < 1 mA

## Part 1: sample ADC0 exactly 10 times a second from the timer interrupt, toggling P0 at each sample, and sleep between samples.

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1;
    while (1) {
        ADC_CTRL = 0 | ADC_START;
        while (!(ADC_STATUS & ADC_DONE)) ;
        ADC_STATUS = ADC_DONE;
        GPIO_TOGGLE = 1;
    }
}
```

```c solution
#include "board.h"

volatile int last = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    ADC_CTRL = 0 | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    last = ADC_DATA;
    GPIO_TOGGLE = 1;
}

int main(void) {
    GPIO_DIR = 1;
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    while (1)
        __wfi();
}
```

::: right
Right. Exactly 100 ms apart, and asleep in between.
:::
:::

::: check
kind: c
given: OFFSET = -50 | 0 | 100
run: 0.01
expect: print = 227 + OFFSET, 240 + OFFSET, 233 + OFFSET

## Part 2: the readings are below, each plus `OFFSET` ({OFFSET}). Print their minimum, their maximum and their average rounded to the nearest whole tenth, in integer arithmetic.

```c starter
#include "board.h"

const int16_t r[10] = {231, 228, 240, 236, 229, 233, 238, 227, 235, 232};

int main(void) {
    print(0);
    print(0);
    print(0);
    return 0;
}
```

```c solution
#include "board.h"

const int16_t r[10] = {231, 228, 240, 236, 229, 233, 238, 227, 235, 232};

int main(void) {
    int lo = r[0] + OFFSET, hi = lo, sum = 0;
    for (int i = 0; i < 10; i++) {
        int v = r[i] + OFFSET;
        if (v < lo) lo = v;
        if (v > hi) hi = v;
        sum += v;
    }
    print(lo);
    print(hi);
    print((sum + 5) / 10);
    return 0;
}
```

::: right
Right. Min and max start from the first reading, and the average rounds.
:::
:::

::: check
kind: c
given: W = 0 | 7 | 23 | 104; D = 0 | 5 | 9
attach: terminal
run: 0.01
expect: terminal = "T={W}.{D}\n"

## Part 3: send `T=` and the value `W * 10 + D` tenths of a degree ({W}.{D}) as a decimal number with one decimal place, then a newline.

```c starter
#include "board.h"

void putc(char c) { while (UART_STATUS & UART_TX_FULL) ; UART_DATA = c; }

int main(void) {
    UART_BAUDDIV = 87;
    putc('T'); putc('=');
    putc('0' + (W * 10 + D) % 10);
    putc('\n');
    return 0;
}
```

```c solution
#include "board.h"

void putc(char c) { while (UART_STATUS & UART_TX_FULL) ; UART_DATA = c; }

void put_tenths(int v) {
    if (v < 0) { putc('-'); v = -v; }
    char d[6]; int k = 0;
    int whole = v / 10;
    do { d[k++] = '0' + whole % 10; whole /= 10; } while (whole);
    while (k) putc(d[--k]);
    putc('.');
    putc('0' + v % 10);
}

int main(void) {
    UART_BAUDDIV = 87;
    putc('T'); putc('=');
    put_tenths(W * 10 + D);
    putc('\n');
    return 0;
}
```

::: right
Right: the whole part's digits in order, a point, then the tenth.
:::
:::

::: explain
## Why does the logger do its sampling in an interrupt but its reporting in the main loop?

::: model
Sampling has to happen at exactly the same interval every time, or the readings' timing is wrong (lesson 39), and it's short: a conversion and a table lookup. The interrupt delivers that precision whatever else is going on. Reporting is slow (each character waits about 87 µs for the UART) and not time-critical: a report a few milliseconds late doesn't matter. Doing it in the interrupt would hold off the next samples and other interrupts for milliseconds, so it belongs in the main loop, which picks up the readings the interrupt has stored and then goes back to sleep.
:::
:::

::: practice

::: check
given: f = 20 | 200; c = 300 | 800
answer: 100*f*c/1e7
unit: %
tolerance: 0.5%

## Load of a {c}-cycle ISR at {f} Hz?

::: misses
- [any] f × c / 10⁷.
:::
:::

::: check
given: f = 5 | 25; s = 30 | 120; b = 2
answer: f*s*b
unit: bytes
tolerance: 0

## RAM for {s} s at {f} Hz, {b} bytes each?

::: misses
- [any] f × s × b.
:::
:::

::: check
given: s = 512 | 3000; N = 8 | 16
answer: floor((s + floor(N/2))/N)
tolerance: 0

## Rounded average of {N} readings summing to {s}?

::: misses
- [any] (s + N/2) / N.
:::
:::
:::
