stm32f4-bare-metal: Ten Register-Level STM32F401 Examples and a USB Console on a Black Pill
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:
- Output over USB. Without an adapter, the only way to print text is the OTG FS peripheral of the F401. So the first real example is a USB CDC-ACM device written at register level, and every later example uses it as its console.
- Flashing over USB. The usual cheap ST-LINK V2 clone works, but its SWD connection over dupont wires turned out to be unreliable. The F401 has a USB DFU bootloader in ROM, so the project flashes through the same cable, and the firmware can be told to jump into that bootloader.
- Registers only. Each
main.cshows exactly what the hardware needs, with the reference manual section in mind. CMSIS headers give the register names; nothing else is hidden. - Measured, not assumed. Every example is tested on the board and the README reports what it measured, including the surprises.
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)
| Example | What it shows |
|---|---|
01-clock-pll | 16 MHz HSI to 84 MHz from the 25 MHz crystal, 48 MHz for USB, flash wait states |
02-usb-cdc | USB CDC-ACM device on the OTG FS core: a serial port on the USB-C connector |
03-exti-button | KEY on EXTI, both edges, debounce in the main loop, bounces counted |
04-iwdg | independent watchdog, reset cause from RCC->CSR, real timeout measured |
05-flash-persistent | append-only records in flash sector 5 with the hardware CRC unit |
06-rtc-backup | RTC on the 32.768 kHz crystal, alarm, 1 Hz wakeup, backup registers |
07-adc-internal | VDDA and chip temperature: ADC scan mode, circular DMA, factory calibration |
08-timer-capture | TIM5 input capture measuring LSI and LSE through internal remaps, no wires |
09-mpu-faults | MPU NULL and stack guards, fault handlers, dumps for a fault decoder |
10-system-console | all 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:
- VBUS sensing off. The Black Pill does not route VBUS to PA9, so
GCCFG.NOVBUSSENSmust be set, or the core never sees a session. - FIFO RAM is yours to split. The F401 has 1.25 KB (320 words) of FIFO RAM: 128 words for the shared RX FIFO, then 16, 64 and 16 words for the EP0, EP1 and EP2 TX FIFOs.
SET_ADDRESSbefore the status stage. The DWC2 core wants the new address inDCFG.DADas soon as the request arrives; it applies it after the status stage on its own.- Zero-length packets. A bulk IN transfer that ends exactly on a 64-byte boundary must be followed by a zero-length packet, otherwise the host waits for more data. Control replies shorter than requested need the same treatment.
- Flow control instead of drops. EP1 OUT is re-armed only when the RX ring has room for a full packet; until then the core NAKs and the host simply waits.
rx_overflowis counted and stays at 0.
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:
- The request is handled in the USB interrupt, right after the status stage of
SET_LINE_CODING. It works even when the application's main loop is stuck, which is exactly when you need to re-flash. - The firmware does not jump into ROM from a running application, with PLL, interrupts and peripherals active. It writes a magic word into a
.noinitRAM section (not cleared by the startup code) and resets. Right after the reset, before the clock is touched,board_init()sees the word, maps system memory withSYSCFG->MEMRMP, loads the bootloader's stack pointer and jumps to its reset vector, with the chip in the state the bootloader expects.
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:
- Watchdog. A "1 second" IWDG (LSI / 32, reload 999) fired 929 ms after the last refresh. Example 08 measured the LSI at 34.47 kHz with a timer, which predicts 928 ms: two methods, the same answer. The F401's LSI may be anywhere between 17 and 47 kHz, so size watchdog timeouts for the range, not for 32 kHz.
- Contact bounce. 24 presses of the KEY button produced 26 extra edges, 23 of them on release; the worst single release gave 11 edges. A 20 ms debounce lost no presses, which lasted 85-145 ms.
- Stack guard size. A 32-byte MPU guard below the stack did not catch a recursion whose frames were about 150 bytes: each frame skipped over the guard without writing into it, and the stack silently overwrote
.bss. With a 1 KB guard every overflow became a MemManage fault withMSTKERR. The guard must be larger than the largest stack frame. - Supply voltage. VDDA read 3.283 V, then 3.218 V ten minutes later on the same USB port. The temperature is therefore computed from the measured VDDA, using the factory calibration values, not from an assumed 3.3 V.
- Crystals. The RTC on the 32.768 kHz crystal gained 94 ms in 7 minutes against the Mac's NTP-disciplined clock, about +224 ppm or 19 s a day. With the +136 ppm measured between the two crystals by example 08, the 25 MHz crystal is about +88 ppm. Both are well outside the usual ±20 ppm; on this board the load capacitors are not matched to the crystals. If wall-clock time matters, calibrate the RTC with the smooth calibration register (
RTC_CALR). - Release builds. Testing the -O2 binaries before the v1.0 release showed the boot counter stuck: every new flash log record had a bad CRC and was skipped. The CRC was computed with
crc32_words(&r.seq, 3), reading three words starting at the first member of the struct. Reading past a member through that pointer is undefined behaviour, and GCC used that freedom to compute the CRC before storingbootsandvalue. The Debug build happened to work. Feeding the three fields to the CRC unit one by one fixed it. Test the binary you ship, not only the one you debug.
Build, flash and fork
What you need
- A WeAct Black Pill STM32F401CC or CE and a USB-C cable that carries data.
arm-none-eabi-gcc, CMake and Ninja; STM32CubeProgrammer forSTM32_Programmer_CLI. On macOS the copies installed by the VS Code STM32Cube extension are found automatically bytools/env.sh.- An ST-LINK is optional.
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
- 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. - Create
examples/11-your-thing/with amain.cand a one-lineCMakeLists.txtcallingadd_example(). The top-level CMake picks the folder up automatically. - Use
console.hfor 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. - Keep flash sector 5 (0x08020000) free for data, or move
DATAincommon/stm32f401cc.ld.
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
- ST, RM0368 STM32F401xB/C and STM32F401xD/E reference manual: RCC, FLASH, PWR, RTC, ADC, DMA, TIM, IWDG, EXTI, CRC and USB OTG FS chapters.
- ST, STM32F401xC datasheet: temperature sensor and VREFINT calibration values, LSI frequency range.
- ST, PM0214 STM32 Cortex-M4 MCUs and MPUs programming manual: MPU, fault status registers, SCB.
- ST, AN2606 STM32 microcontroller system memory boot mode: bootloader entry and USB DFU on STM32F401.
- USB-IF, Universal Serial Bus Specification 2.0, chapter 9, and CDC 1.2 / PSTN 1.2 for the ACM requests.
- Repository: github.com/carresed/stm32f4-bare-metal (MIT), and the fault decoder its dumps are made for: cortex-m-fault-decoder.
- Related on this blog: RCC, PLL and flash latency, IWDG in production, flash write and erase, the STM32 system bootloader.
Reply to this article by email — I read and respond to every message.