Projects / Data logger / Phase 2
Phase 2 of 4 · about 2.5 hours
Keep time and take a reading
You end with a reading from the chip's temperature sensor every second, with a timestamp, turned into degrees by code you tested on your laptop first.
Two things are missing before we can log anything: a clock, so we know when a reading was taken, and a reading. We also need to print numbers, and there is no printf.
Step 2.1: Print numbers, tested on your laptop (about 30 minutes)
We linked no C library, so there is no printf. You could add one, but a full printf is several kilobytes and we only need two things: whole numbers, and temperatures with two decimals. Create fmt.h:
/* Turn numbers into text. Each function writes into buf and returns the length. */
#ifndef FMT_H
#define FMT_H
#include <stdint.h>
int fmt_u32(char *buf, uint32_t value);
int fmt_centi(char *buf, int32_t hundredths);
#endif
And fmt.c:
#include "fmt.h"
int fmt_u32(char *buf, uint32_t value)
{
char digits[10];
int n = 0;
do {
digits[n++] = (char)('0' + value % 10);
value /= 10;
} while (value != 0);
for (int i = 0; i < n; i++)
buf[i] = digits[n - 1 - i];
buf[n] = '\0';
return n;
}
/* 2345 becomes "23.45" and -5 becomes "-0.05". */
int fmt_centi(char *buf, int32_t hundredths)
{
int len = 0;
uint32_t magnitude = (uint32_t)hundredths;
if (hundredths < 0) {
buf[len++] = '-';
magnitude = 0u - magnitude;
}
len += fmt_u32(buf + len, magnitude / 100);
buf[len++] = '.';
buf[len++] = (char)('0' + magnitude / 10 % 10);
buf[len++] = (char)('0' + magnitude % 10);
buf[len] = '\0';
return len;
}
We keep temperatures as whole numbers of hundredths of a degree, so 23.45 degrees is 2345. Integer maths is exact, needs no floating point library, and is fast on any chip. fmt_centi puts the decimal point back when printing.
Look at 0u - magnitude. The obvious -hundredths overflows for the most negative int32_t, because +2147483648 does not fit. Doing the negation on an unsigned number is defined to wrap, and it gives the right magnitude.
Nothing in fmt.c touches hardware, so you can test it on your laptop, where you have a debugger and printf. Keep as much code like this as you can. Create a tests folder and tests/test_fmt.c:
#include <stdio.h>
#include <string.h>
#include "../fmt.h"
static int failures;
static void check(const char *got, const char *want)
{
if (strcmp(got, want) != 0) {
printf("FAIL: got \"%s\", want \"%s\"\n", got, want);
failures++;
}
}
int main(void)
{
char buf[16];
fmt_u32(buf, 0); check(buf, "0");
fmt_u32(buf, 42); check(buf, "42");
fmt_u32(buf, 4294967295); check(buf, "4294967295");
fmt_centi(buf, 2345); check(buf, "23.45");
fmt_centi(buf, 7); check(buf, "0.07");
fmt_centi(buf, -5); check(buf, "-0.05");
fmt_centi(buf, -1250); check(buf, "-12.50");
fmt_centi(buf, -2147483647 - 1); check(buf, "-21474836.48");
printf("%s\n", failures ? "fmt: FAILED" : "fmt: all passed");
return failures != 0;
}
Run it with your normal compiler:
mkdir -p build/host
gcc -std=c11 -Wall -Wextra -o build/host/test_fmt tests/test_fmt.c fmt.c
./build/host/test_fmt
fmt: all passed
Step 2.2: A millisecond clock (about 30 minutes)
Every Cortex-M core has a small timer called SysTick. It counts down from a value you choose, once per clock cycle. When it reaches zero it reloads and raises an interrupt: the core stops what it is doing, runs the handler from entry 15 of the vector table, and goes back. If we reload it every CPU_HZ / 1000 cycles, the handler runs once a millisecond.
Add the handler to the vector table in startup.c. Next to the other aliases:
void SysTick_Handler(void) __attribute__((weak, alias("Default_Handler")));
And in the table, after HardFault_Handler:
[15] = SysTick_Handler,
[15] = is a C99 designated initializer. It puts the entry at index 15 and fills the gap with zeros. Create ticks.h:
#ifndef TICKS_H
#define TICKS_H
#include <stdint.h>
void ticks_init(void);
uint32_t ticks_ms(void);
void ticks_delay(uint32_t ms);
#endif
And ticks.c:
/* A millisecond clock from SysTick, the timer built into every Cortex-M core. */
#include "board.h"
#include "ticks.h"
#define SYST_CSR REG32(0xE000E010u) /* control and status */
#define SYST_RVR REG32(0xE000E014u) /* reload value */
#define SYST_CVR REG32(0xE000E018u) /* current value */
static volatile uint32_t ms_count;
void SysTick_Handler(void)
{
ms_count++;
}
void ticks_init(void)
{
SYST_RVR = CPU_HZ / 1000 - 1; /* count CPU_HZ / 1000 cycles, then interrupt */
SYST_CVR = 0;
SYST_CSR = 7; /* use the CPU clock, interrupt on zero, start */
}
uint32_t ticks_ms(void)
{
return ms_count;
}
void ticks_delay(uint32_t ms)
{
uint32_t start = ms_count;
while (ms_count - start < ms) {
}
}
A 32-bit count of milliseconds wraps back to zero after 49.7 days. ticks_delay survives that, because ms_count - start is unsigned subtraction, and it gives the right gap even across the wrap. Always compare times that way, and never write ms_count >= start + ms.
Pitfall: ms_count is volatile. Try removing that word, build, and look at what the compiler made of ticks_delay:
arm-none-eabi-objdump -d build/qemu/logger.elf | grep -A3 "<ticks_delay>:"
08000170 <ticks_delay>:
8000170: b100 cbz r0, 8000174 <ticks_delay+0x4>
8000172: e7fe b.n 8000172 <ticks_delay+0x2>
8000174: 4770 bx lr
The second instruction jumps to itself forever. The compiler saw that nothing inside the loop changes ms_count, so it read it once and decided the answer could never change. It cannot know that an interrupt changes it. Any variable shared between an interrupt and the rest of the code must be volatile. Put it back.
Step 2.3: Read the temperature sensor (about 35 minutes)
The ADC (analog-to-digital converter) measures a voltage and gives you a number from 0 to 4095, its 12 bits. Every STM32F4 has a temperature sensor inside the chip, wired to one of the ADC's inputs, so you need no extra parts. It measures the chip's own temperature, which runs a few degrees above the room once the chip has been on for a while.
The sensor is on channel 18 on the F401 and channel 16 on the F405 that QEMU pretends to be. QEMU's ADC also has a quirk: it never sets the flag that says a conversion has finished. Add these lines to board.h, inside the BOARD_QEMU part:
#define TEMP_CHANNEL 16 /* the STM32F405 wires its sensor to ADC channel 16 */
#define ADC_SETS_EOC 0 /* QEMU's ADC never reports "conversion done" */
And inside the BOARD_NUCLEO part:
#define TEMP_CHANNEL 18 /* the STM32F401 wires its sensor to ADC channel 18 */
#define ADC_SETS_EOC 1
The ADC needs its clock too. Add this line to board_init in board.c:
RCC_APB2ENR |= 1u << 8; /* clock for ADC1 */
Create adc.h:
#ifndef ADC_H
#define ADC_H
#include <stdint.h>
void adc_init(void);
uint32_t adc_read(void);
#endif
And adc.c:
/* Read the chip's own temperature sensor through ADC1. */
#include "adc.h"
#include "board.h"
#include "ticks.h"
#define ADC1_SR REG32(0x40012000u)
#define ADC1_CR2 REG32(0x40012008u)
#define ADC1_SMPR1 REG32(0x4001200Cu)
#define ADC1_SQR3 REG32(0x40012034u)
#define ADC1_DR REG32(0x4001204Cu)
#define ADC_CCR REG32(0x40012304u)
#define SR_EOC (1u << 1)
#define CR2_ADON (1u << 0)
#define CR2_SWSTART (1u << 30)
#define CCR_TSVREFE (1u << 23)
void adc_init(void)
{
ADC_CCR |= CCR_TSVREFE; /* wake the temperature sensor */
ADC1_SMPR1 |= 7u << (3 * (TEMP_CHANNEL - 10)); /* longest sample time: 480 cycles */
ADC1_SQR3 = TEMP_CHANNEL; /* convert this one channel */
ADC1_CR2 = CR2_ADON; /* ADC on */
ticks_delay(1); /* sensor and ADC need a few microseconds */
}
uint32_t adc_read(void)
{
ADC1_CR2 |= CR2_SWSTART;
if (ADC_SETS_EOC) {
while (!(ADC1_SR & SR_EOC)) {
}
}
return ADC1_DR & 0xFFF; /* 12 bits: 0 to 4095 */
}
TSVREFE powers the sensor up. SMPR1 sets how long the ADC looks at the input before converting. The sensor needs at least 10 microseconds, and the longest setting, 480 ADC clock cycles, gives 60 microseconds at the F401's ADC clock of 8 MHz. SQR3 says which channel to convert. To read, set SWSTART, wait for EOC (end of conversion), and read the result from DR.
Pitfall: an emulator is a model of the chip, and models are incomplete. QEMU's ADC returns made-up numbers that climb by 7 on every read and never sets EOC, so code that waits for EOC hangs forever in QEMU and works on the board. When something works on one and not the other, suspect the model before your code, and check the reference manual to see which one is right.
Step 2.4: From counts to degrees (about 30 minutes)
The sensor's voltage rises in a straight line with temperature, but each chip's line is a little different. So ST measures every chip at the factory, at 30 and 110 degrees, and stores the two ADC readings in a read-only area of memory. Draw a line through those two points and you can turn any reading into degrees.
Add the two values to board.h. Inside the BOARD_NUCLEO part, they are read from the chip:
/* Raw readings ST measured at 30 and 110 degrees, stored in each chip at the factory. */
#define TS_CAL30 (*(const volatile uint16_t *)0x1FFF7A2Cu)
#define TS_CAL110 (*(const volatile uint16_t *)0x1FFF7A2Eu)
QEMU has nothing at those addresses. Reading one there makes the chip fault, so inside the BOARD_QEMU part, use values worked out from the datasheet's typical figures (0.76 V at 25 degrees, rising 2.5 mV per degree, with a 3.3 V supply):
/* QEMU has no factory calibration, so use the datasheet's typical values. */
#define TS_CAL30 959u
#define TS_CAL110 1207u
Create temp.h:
#ifndef TEMP_H
#define TEMP_H
#include <stdint.h>
int32_t temp_centi(uint32_t raw, uint32_t cal30, uint32_t cal110);
#endif
And temp.c:
#include "temp.h"
/*
* Draw a straight line through the two factory points (30 C, cal30) and (110 C, cal110)
* and read off where raw falls. The answer is in hundredths of a degree.
*/
int32_t temp_centi(uint32_t raw, uint32_t cal30, uint32_t cal110)
{
int32_t above = (int32_t)raw - (int32_t)cal30;
int32_t span = (int32_t)cal110 - (int32_t)cal30;
return 3000 + above * 8000 / span;
}
The line goes up 8000 hundredths of a degree over span counts. A reading above counts past the 30 degree point is above * 8000 / span hundredths above 30 degrees. Multiply before you divide, or the integer division throws the detail away. The biggest product is 4095 × 8000, about 33 million, far below the 2.1 billion an int32_t can hold.
Test it on your laptop. Create tests/test_temp.c:
#include <stdio.h>
#include "../temp.h"
static int failures;
static void check(uint32_t raw, int32_t want)
{
int32_t got = temp_centi(raw, 959, 1207);
if (got != want) {
printf("FAIL: raw %u gave %d, want %d\n", raw, got, want);
failures++;
}
}
int main(void)
{
check(959, 3000); /* the 30 degree point */
check(1207, 11000); /* the 110 degree point */
check(1083, 7000); /* halfway between */
check(943, 2484); /* a bit below 30 */
check(0, -27935); /* nonsense in, nonsense out */
printf("%s\n", failures ? "temp: FAILED" : "temp: all passed");
return failures != 0;
}
Check one by hand: 943 is 16 counts below 959, and 16 × 8000 / 248 is 516.1. Integer division gives 516, so the answer is 3000 − 516 = 2484, or 24.84 degrees.
Rather than type the gcc lines every time, add a test target to the Makefile, after the run target:
test:
mkdir -p build/host
gcc -std=c11 -Wall -Wextra -o build/host/test_fmt tests/test_fmt.c fmt.c
gcc -std=c11 -Wall -Wextra -o build/host/test_temp tests/test_temp.c temp.c
for t in $(TESTS); do ./build/host/$$t || exit 1; done
Set the source list and the test list near the top, and add test to the .PHONY line:
SRC = startup.c board.c uart.c ticks.c adc.c fmt.c temp.c main.c
TESTS = test_fmt test_temp
make test
fmt: all passed
temp: all passed
Step 2.5: One reading a second (about 25 minutes)
Replace main.c:
#include "adc.h"
#include "board.h"
#include "fmt.h"
#include "temp.h"
#include "ticks.h"
#include "uart.h"
static void print_reading(uint32_t ms, uint32_t raw, int32_t centi)
{
char num[16];
uart_puts("t=");
fmt_u32(num, ms);
uart_puts(num);
uart_puts(" ms raw=");
fmt_u32(num, raw);
uart_puts(num);
uart_puts(" temp=");
fmt_centi(num, centi);
uart_puts(num);
uart_puts(" C\n");
}
int main(void)
{
board_init();
uart_init();
ticks_init();
adc_init();
uart_puts("logger: booted\n");
uint32_t next = ticks_ms();
for (;;) {
uint32_t now = ticks_ms();
if ((int32_t)(now - next) >= 0) {
next += 1000;
uint32_t raw = adc_read();
print_reading(now, raw, temp_centi(raw, TS_CAL30, TS_CAL110));
led_toggle();
}
}
}
next is the time the next reading is due. Adding 1000 to it, instead of setting it to now + 1000, keeps readings on a one-second grid even when a loop runs late. (int32_t)(now - next) >= 0 is the wrap-safe way to ask "is now at or past next".
make run
logger: booted
t=1 ms raw=7 temp=-277.09 C
t=1001 ms raw=14 temp=-274.83 C
t=2001 ms raw=21 temp=-272.58 C
t=3001 ms raw=28 temp=-270.32 C
The time is right: one reading a second, starting 1 ms in because adc_init waits a millisecond. The temperature is nonsense, colder than anything can be. That is QEMU's made-up ADC climbing by 7, run through a correct conversion. Your laptop tests are what tell you the conversion is right, which is why we wrote them.
On the board: flash it the same way as in Phase 1. Expect raw readings near 950 to 1000 and temperatures in the 20s or low 30s. Put your finger on the chip and watch it rise by a degree or two over half a minute.
Phase 2 done
The logger keeps time with an interrupt, reads a real sensor, and turns counts into degrees with maths you checked on your laptop. All of it still happens in one loop, one thing at a time, and that is the next problem.