stm32f4-bare-metal: Ten Register-Level STM32F401 Examples and a USB Console on a Black Pill

2026-12-03 · Davide Carrese
STM32 · STM32F4 · USB · Register Level · Open Source

A WeAct Black Pill (STM32F401) costs a few euros and has everything on board: a 25 MHz crystal, a 32.768 kHz crystal, a LED, a button and a USB-C connector. stm32f4-bare-metal uses nothing else. Ten examples written against the registers, with no HAL, no CubeMX and no USB stack, all talking to the Mac through the board's own USB port, and a final system console that combines them. This article explains the parts that took real engineering, the numbers the board produced, and how to build, flash and fork the project.

The constraints, and why

Most STM32 examples assume a Nucleo with an ST-LINK virtual COM port, or a USB-serial adapter wired to a UART. I wanted the opposite: a board you can buy anywhere, a USB-C cable, and nothing else. That decision drives the whole design:

Layout

One CMake project, one executable per folder in examples/. A three-line CMakeLists.txt per example lists its sources and the shared modules it uses:

add_example(usb-cdc SOURCES main.c COMMON clock board usb_cdc console)
ExampleWhat it shows
01-clock-pll16 MHz HSI to 84 MHz from the 25 MHz crystal, 48 MHz for USB, flash wait states
02-usb-cdcUSB CDC-ACM device on the OTG FS core: a serial port on the USB-C connector
03-exti-buttonKEY on EXTI, both edges, debounce in the main loop, bounces counted
04-iwdgindependent watchdog, reset cause from RCC->CSR, real timeout measured
05-flash-persistentappend-only records in flash sector 5 with the hardware CRC unit
06-rtc-backupRTC on the 32.768 kHz crystal, alarm, 1 Hz wakeup, backup registers
07-adc-internalVDDA and chip temperature: ADC scan mode, circular DMA, factory calibration
08-timer-captureTIM5 input capture measuring LSI and LSE through internal remaps, no wires
09-mpu-faultsMPU NULL and stack guards, fault handlers, dumps for a fault decoder
10-system-consoleall of the above in one shell over USB

Examples 01-09 are standalone and explain one thing step by step. The reusable versions of the same drivers live in common/ (clock, board, USB CDC, console, RTC, sensors, oscillator measurement, flash log, fault handling), and the system console is built from those.

The USB CDC driver

The F401's OTG FS block is a Synopsys DWC2 core. The driver in common/src/usb_cdc.c is about 600 lines, interrupt driven, with EP0 for control, EP1 bulk IN/OUT for data and EP2 interrupt IN for CDC notifications (declared, never used). The descriptors use ST's virtual COM port VID/PID, so macOS, Linux and Windows 10+ load their built-in CDC driver. The points that matter:

Testing found one real bug. In a 5000-byte echo test two bytes came back wrong, and each wrong byte was an older value from the ring buffer. The write function did tx_buf[tx_head++ & mask] = byte; the compiler was free to update the volatile head index before storing the byte, and when the USB interrupt landed in between it transmitted the stale slot. The fix is the classic single-producer pattern: copy the data, then a barrier (__DMB()), then publish the new index. After the fix, 100 kB echoed back with no byte lost or changed.

Re-flashing without buttons: the 1200 baud touch

Entering the ROM bootloader normally means holding BOOT0 while pressing NRST. The project borrows a trick from Arduino: when the host opens the port at 1200 baud, the firmware reboots into the bootloader. Two details make it robust:

flash.sh then does the rest: it finds the board's port, opens it at 1200 baud, waits for the DFU device and flashes over USB with STM32CubeProgrammer. About two seconds, no button, no probe. If the board is already in the bootloader it flashes directly, and if no USB device shows up it falls back to the ST-LINK. The CLI occasionally hangs after a successful DFU start, so the script stops it once it has reported the start.

What the board measured

The most useful part of testing on hardware is the numbers that differ from the datasheet's typical values:

Build, flash and fork

What you need

First flash

git clone https://github.com/carresed/stm32f4-bare-metal
cd stm32f4-bare-metal
./build.sh                       # every example, into build/Debug/bin/
# hold BOOT0, press and release NRST, release BOOT0 (first time only)
./flash.sh system-console
screen /dev/cu.usbmodem101 115200

From then on ./flash.sh <example> re-flashes over USB by itself. The v1.0 release also has prebuilt .elf and .bin files if you only want to try the console. If the bootloader does not show up on the first BOOT0/NRST attempt, repeat it holding BOOT0 a little longer: on these boards it does not always enter DFU at the first try.

Fork it and add an example

  1. Fork the repository. The GitHub Actions workflow builds every example in Debug and Release with Ubuntu's gcc-arm-none-eabi, so your fork gets CI with no setup.
  2. Create examples/11-your-thing/ with a main.c and a one-line CMakeLists.txt calling add_example(). The top-level CMake picks the folder up automatically.
  3. Use console.h for output: console_opened() to print a banner when a terminal connects, console_readline() for commands, printf() for everything else. The 1200 baud reboot keeps working because it lives in the USB driver.
  4. Keep flash sector 5 (0x08020000) free for data, or move DATA in common/stm32f401cc.ld.
Porting to another F4

On an STM32F411 Black Pill (also a 25 MHz crystal, up to 100 MHz) the code needs a different PLL setting in clock.c that still gives exactly 48 MHz for USB, a check of the voltage scaling and flash wait states for the new frequency in RM0383, and a check of which ADC channel carries the temperature sensor. The OTG FS block and the bootloader entry are the same idea; verify the register details in the reference manual of the part.

How I would use it on a client project

Not as a framework to ship: the examples are deliberately minimal. What carries over to production firmware is the approach. A console with info, reset cause and counters from day one; fault handlers that leave a dump that survives the reset; persistent records with a CRC so a power loss never leaves a half-written value; and measuring the real oscillator, supply and timing of the actual board early, before a watchdog that is 7% short or a crystal 200 ppm off shows up as a field failure.

Sources

💬 Comments by email

Reply to this article by email — I read and respond to every message.