What “bare metal” means here
Most STM32 tutorials start in STM32CubeIDE: you click a pin, generate code and call HAL_GPIO_TogglePin(). That works, but it hides everything that makes the LED turn on. In this project you’ll write every piece yourself:
- a linker script that tells the toolchain where flash and RAM are,
- a startup file that sets up the vector table and prepares memory before
main(), - a main.c that blinks the LED by writing directly to hardware registers.
No HAL, no CMSIS headers and no IDE-generated code. It’s about 60 lines in total, and once you understand them, the vendor libraries become much less mysterious.
The main example targets the Nucleo-F401RE (STM32F401RE, an Arm Cortex-M4), whose user LED LD2 is on pin PA5. A later section covers the popular Blue Pill (STM32F103C8) board, which uses a different GPIO register layout.
What you need
- A board: a Nucleo-F401RE, or a similar Nucleo-64 board with the user LED on PA5 (check your board’s user manual). It has an ST-LINK debugger built in.
- The Arm GNU Toolchain (
arm-none-eabi-gcc), available from Arm’s website and through most Linux and macOS package managers. - A flashing tool: OpenOCD, the open-source
stlinktools (st-flash), or STM32CubeProgrammer. - The documentation: the RM0368 reference manual (for the STM32F401), the device datasheet and the Nucleo board’s user manual, all free from ST’s website.
Find the registers in the reference manual
Every value in this tutorial comes from the reference manual. Learning to look these up is the real skill, because it’s how you’ll port this to any other chip.
To blink PA5 you need three things:
- Turn on the clock to GPIO port A. STM32 peripherals start with their clocks off to save power. The reset and clock control (RCC) block has an enable register for each bus. GPIOA sits on the AHB1 bus, so you set the
GPIOAENbit (bit 0) inRCC_AHB1ENR. - Make PA5 an output. Each GPIO port has a mode register,
GPIOx_MODER, with two bits per pin. For pin 5 those are bits 11:10, and01means general-purpose output. - Drive the pin high and low, using either the output data register (
GPIOx_ODR) or the bit set/reset register (GPIOx_BSRR).
Addresses are given as a base address for each peripheral (in the memory map section of the reference manual or datasheet) plus a register offset (in each peripheral’s register map). For the STM32F401:
| Register | Base | Offset | Address |
|---|---|---|---|
RCC_AHB1ENR |
RCC 0x40023800 |
0x30 |
0x40023830 |
GPIOA_MODER |
GPIOA 0x40020000 |
0x00 |
0x40020000 |
GPIOA_ODR |
GPIOA 0x40020000 |
0x14 |
0x40020014 |
GPIOA_BSRR |
GPIOA 0x40020000 |
0x18 |
0x40020018 |
Double-check these against your own copy of the manual, especially if you’re using a different STM32 part.
Step 1: The linker script
The linker script describes the chip’s memory and says where each section of the program goes. The STM32F401RE has 512 KB of flash starting at 0x08000000 and 96 KB of SRAM starting at 0x20000000.
Save this as stm32f401re.ld:
ENTRY(Reset_Handler)
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 96K
}
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
.isr_vector :
{
KEEP(*(.isr_vector))
} > FLASH
.text :
{
*(.text*)
*(.rodata*)
. = ALIGN(4);
} > FLASH
_sidata = LOADADDR(.data);
.data :
{
. = ALIGN(4);
_sdata = .;
*(.data*)
. = ALIGN(4);
_edata = .;
} > RAM AT > FLASH
.bss :
{
. = ALIGN(4);
_sbss = .;
*(.bss*)
*(COMMON)
. = ALIGN(4);
_ebss = .;
} > RAM
}
What matters here:
ENTRY(Reset_Handler)names the program’s entry point. The hardware doesn’t use it (it reads the vector table instead), but debuggers and the linker do, and without it the linker warns about a missing_startsymbol..isr_vectorgoes first so the vector table lands at the very start of flash, where the Cortex-M core looks for it on reset (in the default boot configuration, flash is aliased to address 0)._estackis the top of RAM. The stack grows downward from there..dataholds initialized global variables. It’s stored in flash (AT > FLASH) but used from RAM, so the startup code must copy it across..bssholds zero-initialized globals. It only exists in RAM, and the startup code must clear it.
Step 2: A minimal startup file
On reset, a Cortex-M core reads two words from the vector table: the initial stack pointer, then the address of the reset handler. It loads the first into the stack pointer and jumps to the second. That means the startup code can be written in plain C.
Save this as startup.c:
#include <stdint.h>
extern uint32_t _estack, _sidata, _sdata, _edata, _sbss, _ebss;
int main(void);
void Reset_Handler(void)
{
uint32_t *src = &_sidata;
uint32_t *dst = &_sdata;
/* Copy initialized data from flash to RAM */
while (dst < &_edata) {
*dst++ = *src++;
}
/* Zero the .bss section */
for (dst = &_sbss; dst < &_ebss; ) {
*dst++ = 0;
}
main();
while (1) { } /* main should never return */
}
/* Minimal vector table: initial stack pointer and reset handler */
__attribute__((section(".isr_vector"), used))
void (* const vector_table[])(void) = {
(void (*)(void))&_estack,
Reset_Handler,
};
A real application has a full table with entries for every exception and interrupt, including handlers like HardFault_Handler. A blink with no interrupts can get away with just these two entries. You’ll need to extend the table once you start using interrupts.
Step 3: main.c — enable the clock, set the pin, toggle
Save this as main.c:
#include <stdint.h>
#define RCC_BASE 0x40023800UL
#define GPIOA_BASE 0x40020000UL
#define RCC_AHB1ENR (*(volatile uint32_t *)(RCC_BASE + 0x30))
#define GPIOA_MODER (*(volatile uint32_t *)(GPIOA_BASE + 0x00))
#define GPIOA_ODR (*(volatile uint32_t *)(GPIOA_BASE + 0x14))
#define LED_PIN 5
static void delay(volatile uint32_t count)
{
while (count--) { }
}
int main(void)
{
/* 1. Enable the clock for GPIOA (GPIOAEN, bit 0) */
RCC_AHB1ENR |= (1U << 0);
(void)RCC_AHB1ENR; /* read back to let the clock enable take effect */
/* 2. Set PA5 to general-purpose output mode (MODER5 = 01) */
GPIOA_MODER &= ~(3U << (LED_PIN * 2));
GPIOA_MODER |= (1U << (LED_PIN * 2));
/* 3. Toggle the LED forever */
while (1) {
GPIOA_ODR ^= (1U << LED_PIN);
delay(500000);
}
}
The dummy read after enabling the clock is a small safety margin. Some STM32 errata sheets note that a peripheral may not respond for a few clock cycles after its clock is enabled, and ST’s own HAL does a similar read-back for that reason.
The delay() loop just burns cycles. After reset, the STM32F401 runs from its 16 MHz internal oscillator (HSI), so this gives a blink of very roughly a few hundred milliseconds. The exact rate depends on the compiler and optimization level, which is why Step 5 replaces it.
Why volatile matters
Each register macro casts an address to a volatile uint32_t * and dereferences it. The volatile tells the compiler that every read and write to that address has side effects and must actually happen, in order.
Without it, the compiler may decide a write that’s never read back is pointless and remove it, or keep a value in a CPU register instead of writing it to the peripheral. Code that works at -O0 and breaks at -O2 is a classic sign of a missing volatile. The delay() counter is volatile for a similar reason: otherwise the optimizer can delete the empty loop entirely.
ODR toggle vs BSRR
GPIOA_ODR ^= (1U << LED_PIN) is a read-modify-write: the CPU reads ODR, flips one bit and writes the whole register back. If an interrupt changed another pin on the same port in between, that change would be lost.
The bit set/reset register (BSRR) avoids this. Writing a 1 to bits 0–15 sets the corresponding pin; writing a 1 to bits 16–31 resets it. Zeros are ignored, so each write affects only the pins you name:
#define GPIOA_BSRR (*(volatile uint32_t *)(GPIOA_BASE + 0x18))
GPIOA_BSRR = (1U << LED_PIN); /* PA5 high: LED on */
GPIOA_BSRR = (1U << (LED_PIN + 16)); /* PA5 low: LED off */
It doesn’t matter for a single blinking LED, but BSRR is the habit to build for real firmware.
Step 4: Build and flash
Compile and link with:
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O0 -g -Wall \
-ffreestanding -nostdlib -T stm32f401re.ld \
startup.c main.c -o blink.elf
-mcpu=cortex-m4 -mthumbtargets the core; Cortex-M only runs Thumb instructions.-nostdlibleaves out the C library and its default startup code, since you’ve provided your own.-T stm32f401re.lduses your linker script.
Check that the vector table landed in the right place:
arm-none-eabi-objdump -h blink.elf
arm-none-eabi-size blink.elf
.isr_vector should be at 08000000. The whole program should be a few hundred bytes.
Then flash it, using whichever tool you installed:
# OpenOCD (flashes the ELF directly)
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg \
-c "program blink.elf verify reset exit"
# or the stlink tools (needs a raw binary)
arm-none-eabi-objcopy -O binary blink.elf blink.bin
st-flash write blink.bin 0x08000000
Nucleo boards also appear as a USB drive. Copying blink.bin onto that drive flashes it, which is handy if you don’t have the other tools yet.
The green LD2 LED should now blink.
Step 5: Replace the busy-wait with SysTick
Every Cortex-M core includes SysTick, a 24-bit down-counter designed for exactly this kind of timing. It’s part of the Arm core rather than an ST peripheral, so its registers are documented in ST’s programming manual for the Cortex-M4 (PM0214) and in Arm’s own documentation:
| Register | Address | Purpose |
|---|---|---|
SYST_CSR |
0xE000E010 |
Control and status: enable (bit 0), interrupt (bit 1), clock source (bit 2), COUNTFLAG (bit 16) |
SYST_RVR |
0xE000E014 |
Reload value |
SYST_CVR |
0xE000E018 |
Current value |
At 16 MHz, 16,000 cycles take 1 ms. SysTick counts from the reload value down to zero, so the reload value is 16,000 − 1. The COUNTFLAG bit sets each time the counter reaches zero and clears when you read the register.
#define SYST_CSR (*(volatile uint32_t *)0xE000E010)
#define SYST_RVR (*(volatile uint32_t *)0xE000E014)
#define SYST_CVR (*(volatile uint32_t *)0xE000E018)
static void delay_ms(uint32_t ms)
{
SYST_RVR = 16000 - 1; /* 1 ms at 16 MHz */
SYST_CVR = 0; /* clear the current value */
SYST_CSR = (1U << 2) | (1U << 0); /* processor clock, enable */
while (ms--) {
while ((SYST_CSR & (1U << 16)) == 0) { } /* wait for COUNTFLAG */
}
SYST_CSR = 0; /* stop the timer */
}
Replace delay(500000) with delay_ms(500) and the LED toggles every half second, regardless of optimization level. If you later raise the system clock using the PLL, update the reload value to match.
Porting to a Blue Pill (STM32F103)
The Blue Pill’s STM32F103C8 is an older Cortex-M3 part, and its GPIO peripheral works differently from the F4’s. The steps are the same but the registers change, so it’s good practice in reading a new reference manual (RM0008 for the F1 series).
The differences:
- LED pin: the onboard LED is on PC13, and it’s active low: driving the pin low turns it on.
- Clock enable: GPIO ports sit on APB2. Set
IOPCEN(bit 4) inRCC_APB2ENR(RCC base0x40021000, offset0x18). - Pin configuration: there’s no MODER. Each pin has four bits split into MODE and CNF fields, in
GPIOx_CRL(pins 0–7) orGPIOx_CRH(pins 8–15). For PC13 that’s bits 23:20 ofGPIOC_CRH. The value0x2(MODE = 10, CNF = 00) means push-pull output, 2 MHz max speed. - Addresses: GPIOC is at
0x40011000, with CRH at offset0x04, ODR at0x0Cand BSRR at0x10. - Memory: 64 KB flash and 20 KB RAM, so set
LENGTH = 64KandLENGTH = 20Kin the linker script. - Clock: the HSI runs at 8 MHz after reset, so use a SysTick reload of 8,000 − 1 for 1 ms.
- Compiler flag: use
-mcpu=cortex-m3, andtarget/stm32f1x.cfgwith OpenOCD.
#define RCC_APB2ENR (*(volatile uint32_t *)(0x40021000UL + 0x18))
#define GPIOC_CRH (*(volatile uint32_t *)(0x40011000UL + 0x04))
#define GPIOC_ODR (*(volatile uint32_t *)(0x40011000UL + 0x0C))
RCC_APB2ENR |= (1U << 4); /* IOPCEN */
(void)RCC_APB2ENR;
GPIOC_CRH &= ~(0xFU << 20); /* clear MODE13 and CNF13 */
GPIOC_CRH |= (0x2U << 20); /* output push-pull, 2 MHz */
GPIOC_ODR ^= (1U << 13); /* toggle PC13 */
Many Blue Pill boards are sold with clone or compatible chips rather than genuine STM32s. They usually run simple code like this, but some flashing tools may refuse them or need extra configuration.
If the LED doesn’t blink
Work through these in order:
- Did it flash? Check the tool’s output for errors and make sure it verified the write.
- Is the vector table at
0x08000000? Check withobjdump -h. If.isr_vectoris missing, thesectionattribute or theKEEP()in the linker script is wrong. - Is the pin right? Check the board’s user manual. Some Nucleo boards put the user LED on a different pin, or need a solder bridge set.
- Clock enabled? Forgetting the RCC enable is the most common cause. Writes to a peripheral with its clock off have no effect.
- MODER bits right? Pin n uses bits 2n+1 and 2n. An off-by-one shift configures the wrong pin.
- Is
volatilethere? If it works at-O0but not-O2, check your register macros and the delay counter. - Is it blinking too fast to see? Increase the delay, or use the SysTick version.
To see what’s happening, attach a debugger. With OpenOCD running in one terminal (openocd -f interface/stlink.cfg -f target/stm32f4x.cfg), start GDB in another:
arm-none-eabi-gdb blink.elf
(gdb) target extended-remote :3333
(gdb) monitor reset halt
(gdb) break main
(gdb) continue
(gdb) x/x 0x40020000
The last command shows the current value of GPIOA_MODER. Step through main() with next and watch the register change. Inspecting registers like this is one of the most useful habits in embedded work.
Where to go from here
You’ve just done by hand what every STM32 project does before main() runs. Some natural next steps:
- Switch to CMSIS device headers. ST’s
stm32f4xx.handstm32f401xe.hdefine every register as a struct field, so you can writeRCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;instead of raw addresses. It’s still bare metal, just with readable names. - Read a button with an interrupt. Configure the Nucleo’s user button (B1, on PC13 on the F401RE board) as an input, route it through EXTI and NVIC, and add its handler to the vector table.
- Raise the clock. Configure the PLL to run the core faster and recalculate your SysTick reload value.
- Write a UART driver so you can print debug messages, the next step toward the driver-writing projects in our list of embedded systems project ideas.
If you’d like a project where libraries do more of the work so you can focus on sensors and networking, try building an ESP32 weather station next.