Projects / Data logger / Phase 1
Phase 1 of 4 · about 2.5 hours
Boot a chip from nothing
You end with firmware you wrote from the first instruction, built with your own Makefile, printing logger: booted in QEMU.
On a laptop, the operating system loads your program, sets up its memory and calls main. On a microcontroller, nobody does that for you. The chip powers up, reads two numbers from a fixed place in flash, and starts running. Everything after that is yours. This phase builds the smallest program that gets from power-on to text on a screen.
Step 1.1: What the chip does at power-on (about 20 minutes)
An STM32 has two kinds of memory that matter to us. Flash keeps its contents with the power off. It holds the program, and on these chips it starts at address 0x08000000. RAM is fast and forgets everything at power-off. It holds variables and the stack, and it starts at 0x20000000. The Nucleo's F401 has 512 KB of flash and 96 KB of RAM. QEMU's F405 has more of both, so a program that fits the F401 also fits QEMU.
When the chip comes out of reset, the processor core (an ARM Cortex-M4) reads the first two 32-bit words of flash:
- The first word is the starting value of the stack pointer. The stack grows downwards, so this is usually the top of RAM.
- The second word is the address of the first instruction to run. That function is called the reset handler.
Those two words are the start of the vector table: a list of addresses, one for each event the core can react to. Entry 15 is the timer every Cortex-M has. Entries from 16 onwards are the chip's own peripherals, such as the serial port. When an event happens, the core looks up its entry and jumps there. We fill in two entries now and add more as we need them.
The reset handler has two jobs before it can call main. A global like int count = 5; must start at 5, but RAM is garbage at power-on. So the linker stores the starting values in flash, and the reset handler copies them into RAM. That area is called .data. Globals with no starting value, such as static int total;, must start at zero. That area is .bss, and the reset handler fills it with zeros.
The chip talks to the outside through peripherals: a serial port, timers, an analog-to-digital converter. Each one is a set of registers at fixed addresses. Writing a number to one of those addresses changes what the hardware does, and reading one tells you its state. There is no driver to call. You look up the address in the reference manual and write to it.
Step 1.2: Tell the linker where memory is (about 25 minutes)
The linker decides where each piece of the program goes. On a laptop it has sensible defaults. Here it needs a linker script. Create link.ld:
/* Where things live on an STM32F401RE. QEMU's chip has more of both, so this fits there too. */
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 96K
}
/* The stack starts at the top of RAM and grows down. */
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH
.text : { *(.text*) *(.rodata*) } > FLASH
.data : {
_sdata = .;
*(.data*)
_edata = .;
} > RAM AT > FLASH
_sidata = LOADADDR(.data);
.bss : {
_sbss = .;
*(.bss*) *(COMMON)
_ebss = .;
} > RAM
}
MEMORY names the two regions and says where they are. _estack is the top of RAM, which becomes the first word of the vector table.
SECTIONS places the program's pieces in order. The vector table goes first in flash, because the core reads it from 0x08000000. Code (.text) and constants (.rodata) go next. .data is the clever one. > RAM AT > FLASH means "this section's addresses are in RAM, but store its bytes in flash". LOADADDR(.data) is where those bytes sit in flash, and the reset handler copies them from there. .bss takes room in RAM and nothing in flash, since it only needs zeros.
Names such as _sdata and _ebss are linker symbols. They have no storage of their own. C code reads their address to find where a section starts and ends.
KEEP matters. We will ask the linker to throw away anything nothing refers to, to keep the program small, and nothing in the code calls the vector table. KEEP stops the linker from deleting it. You will see what happens without it in Step 1.6.
Step 1.3: Write the startup code (about 25 minutes)
Create startup.c:
/* What runs before main: the vector table and the reset handler. */
#include <stdint.h>
/* These symbols come from link.ld. Only their addresses mean anything. */
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
int main(void);
void Reset_Handler(void)
{
/* Copy initial values of global variables from flash to RAM. */
uint32_t *src = &_sidata;
for (uint32_t *dst = &_sdata; dst < &_edata;)
*dst++ = *src++;
/* Globals without a value start at zero. */
for (uint32_t *dst = &_sbss; dst < &_ebss;)
*dst++ = 0;
main();
for (;;) {
}
}
void Default_Handler(void)
{
for (;;) {
}
}
void NMI_Handler(void) __attribute__((weak, alias("Default_Handler")));
void HardFault_Handler(void) __attribute__((weak, alias("Default_Handler")));
__attribute__((section(".isr_vector"), used))
const void *const vector_table[] = {
&_estack, /* 0: where the stack starts */
Reset_Handler, /* 1: the first code to run */
NMI_Handler, /* 2 */
HardFault_Handler, /* 3 */
};
Reset_Handler does the two jobs from Step 1.1 and calls main. If main ever returns, there is nowhere to go, so it loops forever.
vector_table is an array of addresses placed in a section called .isr_vector, which the linker script puts first. used stops the compiler from dropping it for being unused. NMI_Handler and HardFault_Handler are weak aliases of Default_Handler: if no other file defines a function with that name, the name points at the loop. A hard fault is the core's "something went badly wrong" event, such as reading an address that does not exist. Looping there is crude, but you can stop the chip in a debugger and see where it is stuck.
Pitfall: the compiler wants these entries to be functions written for the Thumb instruction set, the only one a Cortex-M runs. The address of a Thumb function has its lowest bit set to 1. If you ever write a handler's address by hand as a number, an even number makes the chip fault the moment it jumps there. Writing the function name, as we do, lets the compiler set that bit for you.
Step 1.4: Turn on the parts you use (about 20 minutes)
Every peripheral on an STM32 starts with its clock off, to save power. A peripheral with no clock ignores whatever you write to it. The block that hands out clocks is the RCC (reset and clock control), and each peripheral has an enable bit in one of its registers.
QEMU and the Nucleo differ in a few ways: the clock speed, and which serial port reaches your screen. Keep all of that in one header. Create board.h:
/* Everything that differs between QEMU and a real board. */
#ifndef BOARD_H
#define BOARD_H
#include <stdint.h>
#define REG32(addr) (*(volatile uint32_t *)(addr))
#if defined(BOARD_QEMU)
#define CPU_HZ 168000000u /* QEMU's netduinoplus2 runs at 168 MHz */
#define UART_BASE 0x40011000u /* USART1, which QEMU connects to your terminal */
#elif defined(BOARD_NUCLEO)
#define CPU_HZ 16000000u /* the internal 16 MHz clock the chip starts on */
#define UART_BASE 0x40004400u /* USART2, wired to the ST-LINK's USB serial port */
#else
#error "Build with make BOARD=qemu or make BOARD=nucleo"
#endif
void board_init(void);
void led_toggle(void);
#endif
REG32 turns an address into something you can read and write. volatile tells the compiler that every read and write must really happen, in order, because the hardware is watching. Without it the compiler may decide a write that is never read back is pointless and delete it.
The Nucleo's USB serial port is wired to USART2. QEMU sends USART1 to your terminal. After reset, the F401 runs from its internal 16 MHz clock, and QEMU's board pretends to run at 168 MHz. We never change the clock, which keeps the code simple.
Create board.c:
/* Turn on the parts of the chip we use. */
#include "board.h"
#define RCC_AHB1ENR REG32(0x40023830u)
#define RCC_APB1ENR REG32(0x40023840u)
#define RCC_APB2ENR REG32(0x40023844u)
#define GPIOA_MODER REG32(0x40020000u)
#define GPIOA_ODR REG32(0x40020014u)
#define GPIOA_AFRL REG32(0x40020020u)
void board_init(void)
{
RCC_AHB1ENR |= 1u << 0; /* clock for GPIO port A */
RCC_APB2ENR |= 1u << 4; /* clock for USART1 */
RCC_APB1ENR |= 1u << 17; /* clock for USART2 */
/* PA5 is the green LED on a Nucleo: make it an output. */
GPIOA_MODER = (GPIOA_MODER & ~(3u << 10)) | (1u << 10);
/* PA2 and PA3 carry USART2: alternate function 7. */
GPIOA_MODER = (GPIOA_MODER & ~(0xFu << 4)) | (0xAu << 4);
GPIOA_AFRL = (GPIOA_AFRL & ~(0xFFu << 8)) | (0x77u << 8);
}
void led_toggle(void)
{
GPIOA_ODR ^= 1u << 5;
}
board_init turns on the clocks, then sets up three pins on port A. Each pin has two bits in GPIOA_MODER: 01 means output and 10 means alternate function, which hands the pin to a peripheral. PA5 is the Nucleo's green LED. PA2 and PA3 are wired to the ST-LINK chip, which turns them into a USB serial port, and alternate function 7 connects them to USART2. The values come from the F401 reference manual (RM0368) and datasheet.
Notice the pattern (reg & ~mask) | value: clear the bits you own, set them to what you want, and leave the rest of the register alone. You will write it a lot.
QEMU does not model these pins, so the writes do nothing there. That is fine. The code is the same on both, and only the board shows the LED.
Step 1.5: Talk over the serial port (about 35 minutes)
A UART sends bytes one bit at a time down a wire, at an agreed speed called the baud rate. 115200 bits a second is a common choice. Create uart.h:
#ifndef UART_H
#define UART_H
void uart_init(void);
void uart_putc(char c);
void uart_puts(const char *s);
#endif
And uart.c:
/* Send text out of the serial port, one character at a time. */
#include "board.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_TXE (1u << 7) /* the data register is free for the next character */
#define CR1_UE (1u << 13) /* USART on */
#define CR1_TE (1u << 3) /* transmitter on */
void uart_init(void)
{
USART_BRR = (CPU_HZ + 115200 / 2) / 115200; /* 115200 baud */
USART_CR1 = CR1_UE | CR1_TE;
}
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++);
}
USART_BRR sets the speed. The chip divides its clock by this number to get the baud rate, so at 16 MHz it is 16000000 / 115200, which rounds to 139. That gives 115108 baud, close enough: serial ports cope with an error of a couple of percent. CR1_UE | CR1_TE switches the USART and its transmitter on.
uart_putc waits until the TXE flag says the data register is free, then writes the character. At 115200 baud one character takes about 87 microseconds, so the wait is real on a board. A serial terminal expects a carriage return before each new line, so \n sends \r\n.
Now main.c:
#include "board.h"
#include "uart.h"
int main(void)
{
board_init();
uart_init();
uart_puts("logger: booted\n");
for (;;) {
led_toggle();
for (volatile uint32_t i = 0; i < 400000; i++) {
}
}
}
The loop toggles the LED, then counts to 400,000 to waste time. The counter is volatile so the compiler keeps the loop. At 16 MHz that is roughly a quarter of a second per toggle on the board.
Step 1.6: Build it and run it (about 25 minutes)
Create the Makefile. Make wants a tab, not spaces, at the start of each command line.
BOARD ?= qemu
BUILD = build/$(BOARD)
CC = arm-none-eabi-gcc
CFLAGS = -mcpu=cortex-m4 -mthumb -Os -g -std=c11 -Wall -Wextra -ffreestanding
LDFLAGS = -nostdlib -T link.ld -Wl,--gc-sections -lgcc
ifeq ($(BOARD),qemu)
CFLAGS += -DBOARD_QEMU
else ifeq ($(BOARD),nucleo)
CFLAGS += -DBOARD_NUCLEO
else
$(error BOARD must be qemu or nucleo)
endif
SRC = startup.c board.c uart.c main.c
$(BUILD)/logger.elf: $(SRC) $(wildcard *.h) link.ld Makefile
mkdir -p $(BUILD)
$(CC) $(CFLAGS) $(SRC) $(LDFLAGS) -o $@
arm-none-eabi-size $@
$(BUILD)/logger.bin: $(BUILD)/logger.elf
arm-none-eabi-objcopy -O binary $< $@
bin: $(BUILD)/logger.bin
run: $(BUILD)/logger.elf
qemu-system-arm -M netduinoplus2 -nographic -kernel $<
clean:
rm -rf build
.PHONY: bin run clean
The flags are worth reading once:
-mcpu=cortex-m4 -mthumbbuilds for the core in both chips.-ffreestandingtells the compiler there is no operating system and no standard library to assume.-nostdliblinks nothing we did not write, except-lgcc, the compiler's own helper routines.-Wl,--gc-sectionsdrops code that nothing uses.BOARD=qemuorBOARD=nucleopicks the build, and each one goes in its own folder, so switching never mixes them.
Build it:
make
The last lines are the size table:
text data bss dec hex filename
320 0 0 320 140 build/qemu/logger.elf
The whole program is 320 bytes of flash. Look at the first 16 bytes, the vector table:
arm-none-eabi-objdump -s -j .isr_vector build/qemu/logger.elf
Contents of section .isr_vector:
8000000 00800120 13000008 11000008 11000008 ... ............
The words are stored lowest byte first. The first is 0x20018000, the top of 96 KB of RAM. The second is 0x08000013: the reset handler sits at 0x08000012, plus 1 for Thumb. Now run it:
make run
logger: booted
QEMU keeps running, because the program never ends. To quit, press Ctrl-A, let go, then press X.
Now break it on purpose. In link.ld, change KEEP(*(.isr_vector)) to *(.isr_vector), then make and make run:
text data bss dec hex filename
0 0 0 0 0 build/qemu/logger.elf
qemu: fatal: Lockup: can't escalate 3 to HardFault (current priority -1)
Zero bytes. Nothing refers to the vector table, so --gc-sections removed it. Then nothing refers to the reset handler, so that went too, and so on until the program was gone. The chip read garbage as its first address and locked up. Put KEEP back.
On the board: build with make BOARD=nucleo bin. Plug in the Nucleo and it shows up as a USB drive called something like NOD_F401RE. Copy build/nucleo/logger.bin onto it, and the ST-LINK programs the chip and resets it. Open the serial port with screen /dev/ttyACM0 115200 on Linux or screen /dev/cu.usbmodem* 115200 on a Mac (Ctrl-A then K quits screen). Press the black reset button, and you should see logger: booted and the green LED blinking.
Phase 1 done
You have firmware with nothing underneath it. You placed every section yourself, wrote the code that runs before main, and drove a serial port by writing to its registers.