Skip to content
systemcoding.dev
Embedded

Write a Minimal Bare-Metal Blinky for STM32 Without a HAL

Build an STM32F4 blinky with no HAL: one C file, a short linker script, a vector table and the arm-none-eabi-gcc commands that produce a flashable binary.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the STMicroelectronics, Arm and GNU logos.

A vendor HAL hides how little a blinking LED needs. On an STM32F407 Discovery board the whole program is one C file, a linker script of about twenty lines, and a compiler command. No SDK, no generated project and no startup file from the vendor. This post builds exactly that, for the STM32F407VG on the STM32F4DISCOVERY board with arm-none-eabi-gcc 13.2 from the Arm GNU Toolchain, and explains each piece as it appears. The reset sequence this program relies on is the same one every Cortex-M part follows: two words from the vector table, then the reset handler.

The board's green LED (LD4) is on pin PD12. Lighting it takes three register writes: enable the clock to GPIO port D, set PD12 as an output, and toggle its output bit in a loop.

The registers, from the reference manual

All addresses and bit positions come from RM0090, the STM32F405/407/415/417 reference manual. Three registers matter:

RegisterAddressWhat we write
RCC_AHB1ENR0x40023830Bit 3 (GPIODEN) enables the clock to port D
GPIOD_MODER0x40020C00Bits 25:24 = 01 makes PD12 a general-purpose output
GPIOD_ODR0x40020C14Bit 12 drives PD12

A peripheral on STM32 does nothing until its clock is enabled. Writes to GPIOD_MODER with the clock off are simply ignored, and the pin stays an input. That is the most common reason a first blinky stays dark.

The C file

We define the registers as volatile pointers so the compiler never optimises the accesses away, and we write the vector table and reset handler in the same file. The whole program:

blink.cc
#include <stdint.h>

#define RCC_AHB1ENR (*(volatile uint32_t *)0x40023830u)
#define GPIOD_MODER (*(volatile uint32_t *)0x40020C00u)
#define GPIOD_ODR   (*(volatile uint32_t *)0x40020C14u)

extern uint32_t _estack;
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;

int main(void);

void Reset_Handler(void)
{
	uint32_t *src = &_sidata;
	uint32_t *dst = &_sdata;

	while (dst < &_edata)
		*dst++ = *src++;
	for (dst = &_sbss; dst < &_ebss; )
		*dst++ = 0;

	main();
	for (;;)
		;
}

void Default_Handler(void)
{
	for (;;)
		;
}

__attribute__((section(".isr_vector"), used))
const uint32_t vectors[] = {
	(uint32_t)&_estack,        /* initial stack pointer */
	(uint32_t)Reset_Handler,   /* reset */
	(uint32_t)Default_Handler, /* NMI */
	(uint32_t)Default_Handler, /* HardFault */
};

static void delay(volatile uint32_t n)
{
	while (n--)
		;
}

int main(void)
{
	RCC_AHB1ENR |= (1u << 3);              /* clock to GPIOD */
	(void)RCC_AHB1ENR;                     /* read back: let the clock settle */

	GPIOD_MODER &= ~(3u << 24);            /* clear mode bits for PD12 */
	GPIOD_MODER |=  (1u << 24);            /* 01 = output */

	for (;;) {
		GPIOD_ODR ^= (1u << 12);
		delay(500000);
	}
}

The delay is a busy loop on a volatile counter. With no clock configuration the core runs from the 16 MHz internal oscillator (HSI) after reset, so half a million iterations take a visible fraction of a second. The exact blink rate depends on the compiler's code for the loop and is not a measurement you should rely on.

The read-back of RCC_AHB1ENR is deliberate. ST's errata and reference manual note that there is a short delay between enabling a peripheral clock and the peripheral responding, and a dummy read of the enable register is the documented way to cover it.

The vector table has only four entries. The core reads the first two at reset. The other two exist so a fault lands in a loop you can find in a debugger instead of reading past the table. Interrupts you never enable are never taken.

The linker script

The program needs a script that places the vector table first in flash and defines the symbols the reset handler uses:

link.ldText
ENTRY(Reset_Handler)

MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 1024K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}

_estack = ORIGIN(RAM) + LENGTH(RAM);

SECTIONS
{
  .text :
  {
    KEEP(*(.isr_vector))
    *(.text*)
    *(.rodata*)
    . = ALIGN(4);
  } > FLASH

  _sidata = LOADADDR(.data);

  .data :
  {
    _sdata = .;
    *(.data*)
    . = ALIGN(4);
    _edata = .;
  } > RAM AT > FLASH

  .bss :
  {
    _sbss = .;
    *(.bss*)
    *(COMMON)
    . = ALIGN(4);
    _ebss = .;
  } > RAM
}

The STM32F407VG has 1 MiB of flash at 0x08000000 and 128 KiB of main SRAM at 0x20000000 (the separate 64 KiB CCM RAM is ignored here). _estack is the end of RAM. KEEP on the vector section stops --gc-sections from discarding a table nothing references. > RAM AT > FLASH is the line that gives .data a run address in RAM and a load address in flash, and LOADADDR(.data) is how the reset handler finds the flash copy. The GNU ld manual describes these in its sections on MEMORY, SECTIONS and the AT keyword.

This program has no initialised globals, so both copy loops do no work. They stay because the first global you add depends on them.

The compile options for a Cortex-M4 are the part that trips people up:

Text
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -Os -g \
    -ffunction-sections -fdata-sections \
    -nostdlib -Wl,-T,link.ld -Wl,--gc-sections \
    blink.c -o blink.elf
arm-none-eabi-objcopy -O binary blink.elf blink.bin
arm-none-eabi-size blink.elf

-mcpu=cortex-m4 -mthumb generates Thumb-2 code for the core. Without -mthumb, GCC for Arm targets can emit Arm-state instructions that a Cortex-M cannot execute. -nostdlib leaves out the C library and its startup files, since this program supplies its own. We use no floating point, so no FPU option is needed.

arm-none-eabi-size prints a table whose columns are code, initialised data, zero-initialised data, and their total. For this program it is tiny, on the order of a hundred bytes of text:

Text
   text	   data	    bss	    dec	    hex	filename
    132	      0	      0	    132	     84	blink.elf

The exact figure depends on the compiler version and optimisation level. A data and bss of zero is expected because the program has no globals.

Flashing

With OpenOCD and an ST-LINK on the Discovery board, one command writes the file:

Text
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg \
    -c "program blink.elf verify reset exit"

OpenOCD reads the ELF, writes each loadable segment to its load address, verifies it, resets the core and exits. After the reset the core reads vectors[0] and vectors[1] and the green LED starts blinking. A typical tail of its output ends with:

Text
** Programming Finished **
** Verify Started **
** Verified OK **
** Resetting Target **

Check these in order. If the debugger shows the PC stuck in Default_Handler, a fault happened: usually the vector table is not at the start of flash, so look at arm-none-eabi-objdump -s -j .text blink.elf and confirm the first word is 0x20020000. If the PC is in main but the LED is dark, the clock enable or MODER write is wrong. Read GPIOD_MODER in the debugger: bits 25:24 must be 01. If the LED is always on, the loop is being optimised: check that the counter is volatile.

The program also hides things a real project needs. There is no clock setup, so the core runs at HSI, there is no SysTick, and a full vector table for the part is missing. Those are the topics of the posts after this one.

Why the HAL version is bigger

A HAL blinky for the same board typically drags in the vendor's startup file, a system clock configuration, the HAL's initialisation of SysTick and an interrupt-driven tick counter, plus a generated main.c with error handlers. None of that is wrong, but it hides which parts the LED depends on. The version here depends on three registers and nothing else, so when the LED does not blink, the list of suspects has three entries, not three hundred. Keep this file as a known-good baseline for a new board: if it blinks, the toolchain, linker script, flash tool and clock-gating basics all work, and any later failure is in what you added.

Extending it is mostly mechanical. A second LED is another bit in GPIOD_MODER and GPIOD_ODR (PD13 is bits 27:26 and bit 13). A button on PA0 needs the GPIOA clock (bit 0 of RCC_AHB1ENR) and a read of GPIOA_IDR at 0x40020010, with the pin left in its reset input mode. A precise delay needs a timer or SysTick, which in turn needs an interrupt entry in the table, and that is when the four-entry table grows to the full one.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.