Embedded HandbookApps
All sections › VI. Practice
STM32F103, STM32F407, STM8S · level intermediate · 19 min read
Open in the interactive handbook

48ж. A standalone programmer (loader) for STM8 and STM32: flashing without a computer

In 48д the chip was flashed by a utility on a computer through the factory bootloader. On an assembly line a computer at every workstation is too much: you need a box into which a board is placed, a button is pressed, and a green LED lights up. Such a box is a standalone programmer: its own microcontroller, a firmware image on a memory card or in external Flash, a button, LEDs and a counter.

This section covers: what a standalone programmer consists of; the three routes by which it can put firmware into a chip — the factory bootloader over UART, SWD on STM32 and SWIM on STM8 — and how hard each one is to build; SWD is the main route of the section, taken step by step; a Python model of programming time; the image format, CRC, serial number injection, the log; power, levels and reset; a phone over Bluetooth as the control panel and image store; ready-made options and an honest effort estimate; pitfalls.

Sources (topics only, no retelling of the text): AN3155 (the USART protocol of the STM32 factory bootloader), AN2606 (bootloader entry conditions by family), AN2659 (the STM8 UART bootloader — not every STM8 has it), UM0470 (the SWIM protocol and the STM8 debug module), the Arm debug architecture reference (ADIv5: DP, AP, SWD), reference manuals RM0008 and RM0090 (the Flash controller, option bytes). Timing figures come from our own model, and the chip parameters in it are typical values from datasheets.

Terms used in the documentation

Term Meaning
standalone / offline programmer a programmer that works without a computer
gang programmer a programmer for several boards at once
MEM-AP, TAR, DRW memory access port, address register, data register
flash loader (RAM loader) a Flash programming routine running from RAM
SWIM entry sequence the sequence that enters SWIM mode
ROTF / WOTF read and write "on the fly" over SWIM
option bytes, RDP option bytes, readout protection level
serial number injection inserting a serial number into the image
DHCSR, DEMCR registers for halting the core and catching reset
ATT MTU, Data Length Extension the BLE packet size at the attribute and link level

48ж.1 What a standalone programmer is

A standalone programmer is a small device that flashes a target chip without a computer. Inside: its own microcontroller (usually an STM32 with spare Flash and RAM), image storage (a microSD card or an SPI Flash chip), a "Start" button, two or three LEDs (busy, pass, fail), a counter of flashed boards, sometimes a small display. Outside: a connector to the board: UART, SWD or SWIM, plus power and reset.

Block diagram of a standalone programmer: on the left the image storage (memory card or SPI Flash) with the image file, CRC and counter, in the centre the control microcontroller with the Start button and pass and fail LEDs, on the right the target board; between them three routes: UART to the factory bootloader, SWD to STM32, SWIM to STM8; at the bottom the shared lines power, ground and reset; at the top a phone over Bluetooth sends the image and collects the log

On the line it works like this: the operator puts the board into a fixture with spring-loaded pins, presses the button, the programmer applies power, connects to the chip, erases, writes, verifies, sets readout protection if needed, removes power and lights a green or a red LED. All of it in a few seconds and without a single decision by a person.

What sets such a programmer apart from a debugger on the desk: it asks no questions. The image, address, protection settings and serial number are chosen in advance and sit in a file; anything unexpected means a red LED and a line in the log.

48ж.2 Three routes into the chip

Firmware can be loaded in three ways, and they differ a lot in difficulty.

Route Chips What the chip must allow Difficulty
Factory bootloader over UART STM32; STM8 with a bootloader in ROM bootloader entry: the BOOT0 pin, an option byte or blank Flash low
SWD all STM32 the SWDIO and SWCLK pins are not taken by the firmware, or reset is available medium
SWIM all STM8 one SWIM pin and reset high

The first route is the simplest: the protocol is byte-based, with acknowledgements, and all the hard part — writing Flash — is done by ST's code in system memory. The second requires knowing the Arm debug interface and the Flash controller of the particular family. The third is a single-wire protocol with strict timing requirements that has to be met to the clock cycle.

The main route of this section is SWD: every STM32 has it, it does not depend on what is already written in the chip, and it is the fastest. The factory bootloader and SWIM are covered more briefly, as fallback options.

48ж.3 Route 1: the factory bootloader over UART

On STM32 the protocol is the same as in 48д.5: synchronization with 0x7F, 8E1, replies 0x79 and 0x1F, blocks of up to 256 bytes with an XOR checksum. The programmer only has to repeat the utility from 48д.6 on its own microcontroller: Get, Extended Erase (or Erase), Write Memory in blocks, Read Memory to verify, and at the end Go or a reset. In C this is a few hundred lines on top of a UART driver with timeouts.

How to enter the bootloader without a person. The programmer drives two lines: BOOT0 (held at one) and NRST (a reset pulse). After reset the chip starts from system memory and waits for 0x7F. On families with a software BOOT0 (G4 and newer, see 48д.2) the pin may be absent altogether — then the bootloader opens only on a blank chip or via option bytes. For a production board this is convenient: a fresh chip is blank and enters the bootloader by itself, and after flashing it starts the firmware.

On STM8 the UART bootloader is described in AN2659, but not every chip has it — only those that carry the bootloader code in ROM; check the datasheet. Entry is by a flag in the option bytes or by blank Flash, after reset; the protocol is similar to STM32 (synchronization, acknowledgements, blocks), but on some chips the Flash programming routines must first be loaded into RAM. For an STM8 without a bootloader in ROM route 1 is closed — SWIM remains.

Speed: each Write Memory block is 268 bytes on the line, 25.59 ms at 115 200 bit/s. The model (48ж.6) gives 6.55 s of writing for a 64 KB image and twice as much with read-back verification. Verification can be faster — with a checksum command, if the bootloader supports one, or with your own CRC over the flashed area after the firmware starts.

48ж.4 Route 2: SWD for STM32 — the main route

SWD is two wires, SWDIO and SWCLK, plus ground and preferably NRST. The programmer becomes a debugger: it drives the clock and the packets itself. Each operation is a packet made of a request (8 bits: read or write, DP or AP port, register number, parity), a line turnaround, a 3-bit acknowledgement (OK, WAIT, FAULT), 32 data bits and a parity bit. Everything below is built from such packets.

Step 1. Line reset and switching to SWD. At least 50 clocks with SWDIO at one, the 16-bit JTAG-to-SWD switch sequence, again at least 50 ones and a few zeros. Chips with SWD only do not need the sequence, but it does not hurt — it is always sent.

Step 2. Read DPIDR. The first packet after a line reset reads the debug port ID. An OK reply with correct parity means the link works; no reply means wiring, target power or reset. The DPIDR value tells the port version (it differs between Cortex-M0 and M3/M4) and immediately catches swapped SWDIO and SWCLK.

Step 3. Power up debug. Write the system and debug power-up request bits into CTRL/STAT and wait until both acknowledge bits read as one. At the same time clear the sticky error flags via ABORT — they stay after a previous failed attempt.

Step 4. Select the AP. In SELECT choose AP number 0 (MEM-AP), read its IDR, write a 32-bit access size and address auto-increment into CSW. Now target memory is reached like this: address into TAR, data through DRW; with auto-increment the next DRW writes the next word (within 1 KB — at the boundary TAR is written again).

Step 5. Halt the core under reset. Hold NRST low, write into DHCSR the key 0xA05F in the upper bits with the debug and halt bits, into DEMCR the reset vector catch bit, release NRST. The core halts on the first instruction, and the firmware in the chip has no time to reconfigure the SWD pins, go to sleep or start the watchdog. Check: the halt bit in DHCSR reads as one.

Step 6. Read the chip ID. DBGMCU_IDCODE (at an address that depends on the family) or the device ID — and compare it with the image header. Wrong chip — red LED before any erase.

Step 7. Unlock, erase, program. Here the families diverge, but they fall into groups:

Group Program unit Erase Particulars
F0, F1, F3 half-word 16 bits page of 1 or 2 KB, or mass erase keys 0x45670123, 0xCDEF89AB into FLASH_KEYR; PG bit, wait for BSY
F2, F4, F7 8–64 bits by PSIZE sector of 16–128 KB, or mass erase PSIZE depends on supply voltage; large sectors take seconds to erase
L0, L1 word or half-page page first clear PELOCK, then PRGLOCK — two key pairs
G0, G4, L4, WB double word 64 bits page of 2–4 KB write strictly in word pairs, ECC; errors are flags in FLASH_SR
H7 Flash word 256 bits sector of 128 KB writes through a 32-byte buffer, two banks

The direct way: through TAR/DRW write the Flash controller registers (unlock, program bit), then the data to the Flash address, then poll the busy flag. It works everywhere and needs little code in the programmer, but every poll costs extra SWD packets, and on F1 the time is bounded by 52.5 µs per half-word.

Step 8. A RAM flash loader (the faster option). The programmer places into the target's RAM a small programming routine (a few hundred bytes, its own for each group in the table), two data buffers and a parameter block; it sets PC and SP through DCRSR/DCRDR and releases the halt. While the target writes one buffer, the programmer fills the other over SWD; readiness is a word in the parameter block or the core halting on BKPT. Wire and programming run in parallel, with almost no SWD polling.

Step 9. Option bytes and RDP. Its own OPTKEYR key pair, its own write order, applied by a reset or by the option byte reload bit (on newer families). Readout protection levels: 0 — open (0xAA), 1 — reading over debug is blocked, removing it erases all Flash, 2 — debug disabled for good (0xCC). The programmer sets level 2 only if the image header says so explicitly, and as the very last step: after it the chip can no longer be fixed.

Step 10. Verify by CRC. Reading everything back over SWD is fast (the wire is nearly free), but faster still is to run a CRC-32 over the flashed area in the target's RAM (in software or with the chip's CRC unit) and read one word. Compare with the CRC from the header. Only after a match — RDP, the counter, the log.

Step 11. Release. Clear the halt and the reset catch, pulse NRST — the firmware starts; or leave the target powered off if the board test runs at the next station.

One word-write packet is 46 SWD clocks. At 4 MHz that is 11.50 µs per word. The wire hardly matters: on F103 writing a half-word itself takes tens of microseconds, and that is what sets the time — see the tables in 48ж.6.

What makes this route laborious: each group has its own controller, its own option bytes and its own protection removal sequence. General-purpose debuggers carry a set of descriptions for every family; your own programmer only needs the groups that are on your boards.

48ж.5 Route 3: SWIM for STM8

SWIM is one open-drain wire with a pull-up, plus reset. The protocol is described in UM0470. It has three hard spots.

Entry. The programmer holds reset, then sends a series of pulses of set duration onto the SWIM line (several periods at one frequency, then at another); the chip answers with its own synchronization pulse. Get the durations wrong and the chip simply stays silent.

Bits. Each bit is a low level of different length: short for one, long for zero. At low speed a bit is 22 SWIM clocks, at high speed 10 clocks at 8 MHz, that is 2.75 and 1.25 µs. The chip acknowledges each byte with its own bit, and the programmer must sample that bit in a narrow window. Bit-banging cannot do this reliably — you need a timer with input capture and output compare, or SPI/DMA tuned to the clock.

Commands. There are only three: reset over SWIM (SRST), read on the fly (ROTF), write on the fly (WOTF). Everything else is writing to the registers of the debug module and the STM8 Flash controller through WOTF: halting the core, unlocking Flash with keys, block programming, writing option bytes (including readout protection ROP).

That is why SWIM is the hardest of the three: the protocol is simple in meaning, but it needs exact timing, and errors show up only as a silent chip. Do not approach it without an oscilloscope or a logic analyzer.

48ж.6 Programming time: the model

The model model48g.py computes wire time for each route and adds Flash programming time from typical datasheet parameters. It is an estimate, not a measurement: response delays of the chip and the programmer are not in the model.

The STM32 factory bootloader over UART, 8E1, 256-byte blocks; verification by reading back the same blocks:

Image 57 600 bit/s 115 200 bit/s 115 200, no verify
16 KB 6.55 s 3.28 s 1.64 s
64 KB 26.20 s 13.10 s 6.55 s
128 KB 52.41 s 26.20 s 13.10 s
512 KB 209.64 s 104.82 s 52.41 s

SWD: the wire (46 clocks per word) and F103 programming directly through the controller registers, a half-word in 52.5 µs:

Image SWD wire 1 MHz SWD wire 4 MHz F103 via FPEC, 4 MHz
16 KB 0.19 s 0.05 s 0.48 s
64 KB 0.75 s 0.19 s 1.91 s
128 KB 1.51 s 0.38 s 3.82 s

A RAM flash loader (step 8): wire and programming in parallel, the time is the larger of the two plus 1 KB of wire to fill the pipeline; F407 writes a 32-bit word in 16 µs:

Image F103, RAM loader, 4 MHz F407, RAM loader, x32, 4 MHz F407, RAM loader, x32, 1 MHz
16 KB 0.43 s 0.07 s 0.20 s
64 KB 1.72 s 0.27 s 0.77 s
128 KB 3.44 s 0.53 s 1.52 s

Erasing is not in the tables: F1 pages erase quickly, while F4 sectors of 128 KB take a noticeable fraction of a second or more; take the erase time from the datasheet of your chip.

SWIM: the wire at low and high speed, 128-byte blocks, block programming 6 ms:

STM8 image SWIM wire, low speed SWIM wire, high speed total with block programming
8 KB 0.26 s 0.12 s 0.50 s
32 KB 1.03 s 0.47 s 2.00 s
128 KB 4.10 s 1.86 s 8.01 s

Conclusions: on UART the time is set entirely by the line speed, and read-back verification doubles it — for images above 64 KB verify by CRC. On SWD the wire takes fractions of a second, and the time goes into Flash programming — hence the point of a RAM loader: on F407 it fits 64 KB into 0.27 s. On SWIM half the time is eaten by block programming, and high line speed still pays off.

48ж.7 Image, integrity, serial numbers, log

The image file format on the card is your own, simple and checkable. A header and a body are enough:

Before starting, the programmer computes the file CRC and compares it with the header: a broken file on the card must never reach the chip. After writing — verification against the chip (by reading back or a CRC on the chip side).

Serial number. The programmer keeps a counter in its own non-volatile memory, puts the current number into the image at the given offset before writing (and recomputes the CRC of that block), and increments the counter after a successful verify. The number is not incremented on a failure, or the log will have gaps. It is more convenient to keep the number in a separate Flash page of the target rather than in the firmware body — then the image CRC stays the same for the whole batch.

The log is one line per board in a file on the same card: attempt number, serial number, the chip's unique ID (96 bits on STM32), image CRC, result and error code. Such a log ties a failure to a specific board and chip and shows at which step it failed.

Counters and limits: a cap on the number of flashings per file (protection against an extra batch), a ban on reflashing a chip that is already protected, a lockout when the file CRC does not match the header.

48ж.8 Power, levels and reset

Power. The programmer supplies the target through a current-limited switch: a short circuit on the board must not burn the programmer and must produce a clear error. Before starting it is worth measuring the target voltage and supply current — a board with a reversed part shows up right here.

Levels. STM32 and STM8 run at 3.3 V and at 5 V (some STM8). The programmer's lines go through a buffer powered separately from the target voltage (bidirectional for SWDIO and SWIM), otherwise a 3.3 V programmer will power the target through the pin protection diodes.

Reset. NRST is open drain, with no active high. SWD needs "connect under reset": reset is held while the core is halted — otherwise firmware that reconfigured the SWD pins or went to sleep will not let you connect. For SWIM, reset is part of the entry sequence. For the UART bootloader — reset with BOOT0 raised.

Release order: first let the lines go (high impedance), then remove target power; otherwise the target is powered again through the lines.

48ж.9 A phone over Bluetooth: control panel and image store

Instead of a memory card and buttons, the control side can be a phone: the app stores images and logs and shows progress, while the box is linked to it over BLE and flashes the target over SWD by itself.

BLE link throughput 64 KB 256 KB
MTU 23, 4 packets per 15 ms 5.21 KB/s 12.29 s 49.15 s
DLE 251, 1M PHY, 4 packets per 15 ms 63.54 KB/s 1.01 s 4.03 s
DLE 251, 2M PHY, 6 packets per 15 ms 95.31 KB/s 0.67 s 2.69 s

How many packets per connection interval the phone gives is decided by its stack, not by the programmer; the first row is what you get without increasing the packet size, and then transferring the image takes longer than flashing it over SWD.

Pros: a screen, a clear interface and image selection without a separate display; images reach the phone by mail or from the cloud — no card to carry; the log goes from the phone straight into a shared database; serial numbers are issued by the app from a shared pool, and two programmers will not issue the same number.

Cons: the link drops (the phone went into a pocket, went to sleep, another app took the radio); throughput depends on the phone model; the app is one more program to maintain for two OSes; on the line a phone is easily taken away together with the images.

Recommendation. The phone is the interface and image source, but not a participant in flashing:

48ж.10 Ready-made options and an effort estimate

Before building your own, it is worth knowing what already exists.

An honest estimate for your own programmer (one developer familiar with the family; without enclosure and fixture):

What we build Code size Time Main risk
Route 1, STM32 over UART 0.5–1 thousand lines 1–2 weeks bootloader entry on chips without a BOOT0 pin
Route 1, STM8 over UART 1–1.5 thousand lines 2–3 weeks not every chip has the bootloader
Route 2, SWD, one family 2–3 thousand lines 3–6 weeks connect under reset, option bytes
Route 2, each further family 0.3–1 thousand lines 1–2 weeks its own Flash controller
Route 3, SWIM 2–4 thousand lines 6–10 weeks exact timing, debugging only with instruments
Shared: card, image format, log, numbers 1–2 thousand lines 2–3 weeks log corruption on power loss

The time is until a working prototype on the desk; tuning on the line (fixture, training, rare failures) usually adds as much again.

48ж.11 Pitfalls

The bootloader is silent on a production board. Firmware is already in the chip, there is no BOOT0 pin on the connector, software BOOT0 is off — the bootloader cannot be reached. Plan entry in advance: the BOOT0 pin to a fixture test pad or bootloader entry from the firmware (48д.3).

SWD does not connect after the first flashing. The firmware turned PA13 and PA14 into ordinary pins or went into deep sleep. The cure is connect under reset; without an NRST line on the connector nothing helps except the bootloader.

Readout protection set before verification. There is nothing left to verify, and removing protection erases everything. Order: write, verify, only then RDP.

The serial number counter "jumped". The counter was incremented before verification, and the board failed. Increment only after a successful verify and after the log line is written.

The log is corrupted. Programmer power was removed while writing to the card. Write the log as appended lines with a buffer flush after each board, and check the file system at startup.

The target is powered through the lines. A 3.3 V programmer, no buffer, target power off — the target's LEDs glow faintly through the protection diodes. You need buffers powered from the target and the order "lines to Z, then power".

SWIM works on the desk and fails in the fixture. A long wire, capacitance and a weak pull-up stretch the edges, and the chip does not recognize bits. Shorter wire, stronger pull-up, low SWIM speed for the first commands.

48ж.12 Summary

Next: section 48з "Programmers and debuggers for STM32 and STM8" — which adapters exist, why clones are risky and how to flash from the command line.

Open in the interactive handbook