The Complete Guide to Bootloaders and OTA Updates for MCUs
Learn how a microcontroller bootloader starts, validates and updates firmware, from the Cortex-M reset sequence to safe OTA, rollback and secure boot.

Every connected device eventually needs new firmware. A bug turns up, a protocol changes, a security flaw is disclosed, and a technician with a programmer cannot visit ten thousand units. The thing that makes field updates possible is a small, carefully written program that runs before your application: the bootloader. Get it right and an update is a non-event. Get it wrong and a single power cut turns a fleet of devices into paperweights. This guide builds the subject from nothing. It starts with what a Cortex-M does at reset, then walks through memory layout, linker scripts, image headers, the jump from bootloader to application, receiving an image over a serial line, the update strategies that survive power loss, over-the-air delivery, signing and secure boot, rollback, and the failure modes that catch every team once. The examples use an STM32F407 with arm-none-eabi-gcc 14 and the STM32CubeF4 v1.28 HAL, and the ideas carry over to any Cortex-M part. Code is written, not run, so confirm the addresses and register names against your own reference manual.
What a bootloader is, and what it is not
A bootloader is the first piece of your own code that runs after reset. Its job is deliberately narrow:
Decide whether a valid application is present.
If one is, hand control to it.
If not, or if an update has been requested, receive a new image, write it to flash, and try again.
Everything else belongs elsewhere. A bootloader that grows a user interface, a file system and a network stack has become a second application, with its own bugs and no way to be updated safely. The reason is simple: the bootloader is the one component you usually cannot replace in the field, because replacing it is the one operation with no fallback. If the update fails halfway through rewriting the bootloader itself, nothing exists to recover with. So the rule of thumb is to keep it small, test it far more than the application, and update it rarely or never.
Two kinds of bootloader
Most microcontrollers have a bootloader built in at the factory, and you may write your own on top.
A ROM or system bootloader is programmed by the chip vendor into read-only memory. On an STM32 it lives in a region called system memory, and the chip enters it when the BOOT0 pin is high at reset. It speaks a fixed protocol over UART, USB DFU, I2C, SPI or CAN, and it can read and write your flash. Other families have equivalents: the RP2040 has a ROM that presents the board as a USB mass storage drive when you hold the BOOTSEL button, the ESP32 has a ROM loader that talks over UART, and AVR boards commonly use a small program such as Optiboot that sits in the top of flash. These loaders are excellent for development and for factory programming, and unusable for field updates, because someone has to press a button or move a jumper.
A custom bootloader is yours. It lives in the first sectors of flash, starts at reset, and runs the policy you define: where updates can come from, how images are checked, what happens on failure. Everything in this guide after the first section is about building one, because a custom bootloader is what an over-the-air update needs.
Bootloader versus OTA
The two terms are often mixed up. A bootloader is the code that installs a new image and starts it. Over-the-air (OTA) is the way the image reaches the device: Wi-Fi, cellular, Bluetooth Low Energy, LoRa, a USB stick, an SD card, a CAN bus gateway. OTA is a transport plus a policy about when to download and install. The installation machinery is the same whether the bytes arrive on a UART wire or over HTTPS. That is why this guide spends most of its time on the machinery, and then shows how the transport plugs in.
What the Cortex-M does at reset
To write a bootloader you need to know exactly what the processor does when it starts, because the whole hand-over trick depends on it.
On an Arm Cortex-M3, M4 or M7 (the ARMv7-M architecture), after reset the core reads two 32-bit words from the start of the vector table. The first word is the initial value for the main stack pointer, and the second is the address of the reset handler, with its lowest bit set to mark Thumb code. The core loads the stack pointer, jumps to the reset handler, and begins executing. The vector table address is held in the VTOR register of the System Control Block, and its reset value points at address zero.
On an STM32F407, address zero is not flash directly. The chip aliases flash, system memory or SRAM to address zero depending on the BOOT0 and BOOT1 pins. With BOOT0 low, the main flash at 0x08000000 appears at address zero, so the core reads the stack pointer from 0x08000000 and the reset vector from 0x08000004. That is why every STM32 image starts with a vector table at the very start of flash.
So the memory map after a normal boot looks like this:
0x08000000 initial MSP value (word 0 of the vector table)
0x08000004 reset handler address (word 1)
0x08000008 NMI handler
...Your startup code, executed from the reset handler, copies initialized data from flash to RAM, zeroes the uninitialized variables, calls SystemInit() and then main().
The key insight: an application is just a vector table
Here is the fact the whole bootloader technique rests on. To start an application that lives somewhere else in flash, the bootloader only has to reproduce what the hardware does at reset:
Read the application's initial stack pointer from the first word of its vector table.
Read its reset handler address from the second word.
Tell the core where the application's vector table is, by writing
VTOR.Load the stack pointer.
Jump to the reset handler.
There is no operating system, no loader, no relocation. The application is built as a normal firmware image, linked for a different start address, and the bootloader treats the first two words at that address as a recipe.
Planning the flash layout
The bootloader and the application share the flash, so the first design decision is how to divide it. The STM32F407 has 1 MB in twelve sectors of uneven size. The reference manual lists them: sectors 0 to 3 are 16 KB each (0x08000000 to 0x0800FFFF), sector 4 is 64 KB (0x08010000), and sectors 5 to 11 are 128 KB each, ending at 0x080FFFFF. Because erase works on whole sectors, the layout must put boundaries between regions on sector boundaries.
A simple layout for an in-place update bootloader looks like this:
| Region | Address | Size | Sectors | Purpose |
|---|---|---|---|---|
| Bootloader | 0x08000000 | 32 KB | 0, 1 | Bootloader code |
| Boot info | 0x08008000 | 16 KB | 2 | Flags such as "update requested" and a version log |
| Spare | 0x0800C000 | 16 KB | 3 | Reserved |
| Application | 0x08010000 | 960 KB | 4 to 11 | Header plus application image |
The bootloader gets the first two sectors because the processor expects the vector table at the start of flash. It must be small. If your bootloader outgrows 32 KB, you take another sector and move everything after it, which is why you add a margin at the start.
Notice that the boot info region is its own sector. It holds data that changes (a flag set by the application when it wants an update, the count of failed boots), and flash sectors can only be erased as whole units. Putting a flag that changes often in the same sector as code would force you to erase code to change a flag. The flash and EEPROM guide in this cluster explains why in depth.
An image header in front of the application
Before the application's vector table, put a small header. The bootloader reads it to decide whether an image is valid. It does not rely on the application to say it is valid, because after a failed update the application is exactly the thing you cannot trust.
A useful header carries a magic number so the bootloader can tell a real image from erased flash, a header version so the format can evolve, a firmware version, the length of the image, and a CRC over the image bytes:
#ifndef IMAGE_H
#define IMAGE_H
#include <stdint.h>
#define IMAGE_MAGIC 0x4D435542u /* "MCUB" little endian */
#define IMAGE_HEADER_SIZE 0x200u /* keeps the vector table aligned */
#define APP_BASE 0x08010000u
#define APP_VECTORS (APP_BASE + IMAGE_HEADER_SIZE)
#define APP_LIMIT 0x08100000u /* one past the end of flash */
typedef struct {
uint32_t magic;
uint32_t header_version;
uint32_t fw_version; /* 0x00MMmmpp: major, minor, patch */
uint32_t length; /* bytes of application after the header */
uint32_t crc32; /* CRC-32 of those bytes */
uint32_t reserved[3];
} image_hdr_t;
#endifThe header occupies 512 bytes. That size is not arbitrary. On a Cortex-M the vector table must be aligned to a power of two at least as large as the table, and the STM32F407's 98-entry table needs 512-byte alignment. Placing the vector table at APP_BASE + 0x200 keeps it aligned. The same trick appears in the header of MCUboot, which also reserves 512 bytes.
The application's linker script
The application must be linked for the address where it will actually live. In the GNU linker script, move the origin of the flash region past the header:
MEMORY
{
FLASH (rx) : ORIGIN = 0x08010200, LENGTH = 960K - 0x200
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K
}The application also has to tell the core where its vector table is. The standard STM32 startup file, system_stm32f4xx.c, defines VECT_TAB_OFFSET, and SystemInit() writes it into SCB->VTOR. Set it to the application's offset from the start of flash, so the table is at 0x08010200 and not at 0x08000000:
/* offset of the vector table from FLASH_BASE (0x08000000) */
#define VECT_TAB_OFFSET 0x00010200UIf you forget this, the application starts, enables an interrupt, and the core fetches the handler from the bootloader's vector table instead. The result is a jump into the wrong code at the first interrupt, which is one of the most common symptoms of a new bootloader project: the application runs for a moment and then crashes.
Jumping to the application
With the layout fixed, the hand-over is a short function. It has to leave the chip in a state close to a fresh reset, because the application's startup code expects one.
#include <stdint.h>
#include "stm32f4xx.h"
#include "image.h"
typedef void (*entry_fn)(void);
void boot_jump_to_app(uint32_t vectors)
{
uint32_t sp = *(volatile uint32_t *)(vectors + 0u);
uint32_t reset = *(volatile uint32_t *)(vectors + 4u);
/* the application's stack must be in RAM, the entry point in its image */
if (sp < 0x20000000u || sp > 0x20020000u) return;
if (reset < APP_VECTORS || reset >= APP_LIMIT) return;
__disable_irq();
SysTick->CTRL = 0; /* stop the bootloader's tick */
SysTick->LOAD = 0;
SysTick->VAL = 0;
for (unsigned i = 0; i < 8; i++) { /* clear enables and pending flags */
NVIC->ICER[i] = 0xFFFFFFFFu;
NVIC->ICPR[i] = 0xFFFFFFFFu;
}
SCB->VTOR = vectors;
__DSB();
__ISB();
__set_MSP(sp);
((entry_fn)reset)(); /* never returns */
}The function is only as good as the cleanup in the middle. If the bootloader started a timer, the application inherits a timer interrupt it does not expect. If the bootloader set the clock to 168 MHz with the PLL, the application's SystemInit() may try to reconfigure a PLL that is already locked. The safest policy is to leave nothing running: stop SysTick, disable and clear every interrupt, and, if you used the HAL, call HAL_DeInit() and the HAL_RCC_DeInit() function to put the clocks and peripherals back to their reset state before the jump. If the application's startup does not call HAL_Init() or does not tolerate an already running clock tree, put the clocks back to the reset state.
Two details deserve a sentence each. The check on the stack pointer is a cheap sanity test that the first word really is an address inside the 128 KB of main SRAM on this chip, with the top of RAM (0x20020000) allowed because a full descending stack starts there. Erased flash reads as 0xFFFFFFFF, which fails it. And __set_MSP() followed by a call through a function pointer works because the compiler does not use the stack between them in this function. Some toolchains prefer a small piece of assembly for the final step, to guarantee that no stack access slips in after the stack pointer changes. If your compiler inserts a stack access at that point, move the last two lines into a naked function.
What can go wrong at the hand-over
A failed hand-over produces a few distinctive symptoms.
A hard fault right after the jump usually means the vector table address is wrong,
VTORis misaligned, or the application was linked for a different address than the one you jumped to.The application runs and then hangs at the first interrupt is the
VECT_TAB_OFFSETmistake above.A silent return to the bootloader means the validation failed. Make the bootloader log the reason on a UART, because "it just boots to the bootloader" tells you nothing.
Random misbehavior in timing points to a peripheral or clock left in a different state than the application assumes.
Deciding whether to boot or to update
At reset, the bootloader runs a short decision sequence:
Read the boot info region. Did the application request an update, or did the previous boots fail repeatedly?
Check for an external trigger, such as a held button, if your product has one.
Validate the application image: magic, length bounds, then the CRC.
If everything checks out and no update was requested, jump. Otherwise enter update mode.
Validation is the core of it, so write it carefully. A CRC over the image catches accidental corruption: a truncated download, a flipped bit, an erase that did not complete.
#include <stdint.h>
#include <stdbool.h>
#include "image.h"
uint32_t crc32_sw(const uint8_t *p, uint32_t n)
{
uint32_t crc = 0xFFFFFFFFu;
while (n--) {
crc ^= *p++;
for (int b = 0; b < 8; b++) {
crc = (crc & 1u) ? (crc >> 1) ^ 0xEDB88320u : (crc >> 1);
}
}
return ~crc;
}
bool image_valid(void)
{
const image_hdr_t *h = (const image_hdr_t *)APP_BASE;
if (h->magic != IMAGE_MAGIC) return false;
if (h->length == 0 || h->length > (APP_LIMIT - APP_VECTORS)) return false;
uint32_t crc = crc32_sw((const uint8_t *)APP_VECTORS, h->length);
return crc == h->crc32;
}This is the standard reflected CRC-32 used by zlib, which means a host script written in Python with zlib.crc32() produces the same value. That makes the image-building tool in the next section a few lines long. On a part with a hardware CRC unit the same check runs faster, and the readback and CRC post in this cluster covers that unit and its non-reflected convention.
Two properties make this check safe to rely on. First, the header is written last during an update (more on that in a moment), so an interrupted update leaves a missing or invalid header. Second, the length bound prevents a damaged header from sending the CRC loop across the end of flash.
Why the CRC is not enough
A CRC proves the image was not damaged by accident. It proves nothing about who made it, since anyone can compute a CRC over any file. For a development board that is fine. For a product that can be hijacked by flashing malicious firmware, you need a digital signature, which is the subject of the security section below.
Building an image the bootloader accepts
The build produces a raw binary of the application with arm-none-eabi-objcopy -O binary app.elf app.bin. A host script wraps it with the header:
import struct
import sys
import zlib
MAGIC = 0x4D435542
HEADER_SIZE = 0x200
def build(app_bin, out_path, version):
data = open(app_bin, "rb").read()
crc = zlib.crc32(data) & 0xFFFFFFFF
major, minor, patch = (int(x) for x in version.split("."))
fw_version = (major << 16) | (minor << 8) | patch
header = struct.pack("<8I", MAGIC, 1, fw_version, len(data), crc, 0, 0, 0)
header = header.ljust(HEADER_SIZE, b"\xff")
with open(out_path, "wb") as f:
f.write(header)
f.write(data)
if __name__ == "__main__":
build(sys.argv[1], sys.argv[2], sys.argv[3])Invoked as python3 mkimage.py app.bin app_v1.2.3.img 1.2.3, it writes a file whose first 512 bytes are the header (padded with 0xFF, the erased value, so the padding programs to nothing) followed by the application. The <8I format packs eight 32-bit words in little-endian order, which matches image_hdr_t. The same file serves for programming at the factory and for updating in the field, and the build system should produce it on every release.
Receiving an update over a serial line
The simplest transport is a UART. It is also the one you will use for the first version of any bootloader, since it needs no network stack and can be tested with a USB serial adapter. The protocol needs very little, but it must be robust: bytes are lost, flipped, and duplicated on real wires.
A minimal framed protocol:
| Field | Size | Meaning |
|---|---|---|
| Start | 1 byte | 0x7E |
| Sequence | 1 byte | Frame number, wraps at 256 |
| Length | 1 byte | Payload bytes, up to 64 |
| Payload | 0 to 64 bytes | A slice of the image |
| CRC-16 | 2 bytes | CRC-16/CCITT-FALSE over sequence, length and payload |
The device answers each frame with 0x06 (ACK) when it was accepted and 0x15 (NAK) when it was not, and the host resends on a NAK or a timeout. A frame of length zero marks the end of the image.
#include <stdint.h>
#include <stdbool.h>
extern int uart_getc(uint32_t timeout_ms); /* -1 on timeout */
extern void uart_putc(uint8_t c);
extern bool flash_erase_app(void);
extern bool flash_write(uint32_t addr, const uint8_t *p, uint32_t len);
static uint16_t crc16_ccitt(const uint8_t *p, uint32_t n)
{
uint16_t crc = 0xFFFFu;
while (n--) {
crc ^= (uint16_t)(*p++) << 8;
for (int b = 0; b < 8; b++) {
crc = (crc & 0x8000u) ? (uint16_t)((crc << 1) ^ 0x1021u)
: (uint16_t)(crc << 1);
}
}
return crc;
}
/* returns 1 for a data frame, 0 for the end frame, -1 on error */
static int receive_frame(uint8_t *seq, uint8_t *buf, uint8_t *len)
{
int c = uart_getc(2000);
if (c != 0x7E) return -1;
uint8_t body[2 + 64];
int s = uart_getc(100), l = uart_getc(100);
if (s < 0 || l < 0 || l > 64) return -1;
body[0] = (uint8_t)s;
body[1] = (uint8_t)l;
for (int i = 0; i < l; i++) {
int b = uart_getc(100);
if (b < 0) return -1;
body[2 + i] = (uint8_t)b;
}
int hi = uart_getc(100), lo = uart_getc(100);
if (hi < 0 || lo < 0) return -1;
uint16_t got = (uint16_t)((hi << 8) | lo);
if (crc16_ccitt(body, 2u + (uint32_t)l) != got) return -1;
*seq = body[0];
*len = body[1];
for (int i = 0; i < l; i++) buf[i] = body[2 + i];
return l == 0 ? 0 : 1;
}
bool receive_image(void)
{
uint8_t expect = 0, seq, len, buf[64];
uint8_t header[IMAGE_HEADER_SIZE];
uint32_t got = 0; /* bytes received so far */
uint32_t dst = APP_VECTORS; /* where the next payload goes */
if (!flash_erase_app()) return false;
for (;;) {
int r = receive_frame(&seq, buf, &len);
if (r < 0) { uart_putc(0x15); continue; } /* NAK */
if (seq != expect) { uart_putc(0x06); continue; } /* duplicate: ACK, skip */
if (r == 0) { uart_putc(0x06); break; } /* end of image */
if (got < IMAGE_HEADER_SIZE) {
/* the first 512 bytes are the header: hold them until the end */
for (uint8_t i = 0; i < len; i++) header[got + i] = buf[i];
} else {
/* pad the tail to a whole word with the erased value */
while (len & 3u) buf[len++] = 0xFF;
if (!flash_write(dst, buf, len)) return false;
dst += len;
}
got += len;
expect++;
uart_putc(0x06);
}
/* write the header last: it is what makes the image valid */
return flash_write(APP_BASE, header, IMAGE_HEADER_SIZE);
}The code assumes the sender uses 64-byte frames for everything except the last, so the 512-byte header ends exactly on a frame boundary and every flash write is a multiple of the 4-byte programming unit. The two ideas to take from it are the ones that matter for safety. First, a duplicated frame is acknowledged and skipped, so a lost ACK never causes the same data to be written twice. Second, the header is written last. Until that final call, the application region has no valid header, so if power fails at any earlier moment the next boot finds no valid image and returns to update mode instead of jumping into half an application.
A host-side sender is a short Python script with the pyserial package, version 3.5:
import sys
import time
import serial
def crc16(data):
crc = 0xFFFF
for b in data:
crc ^= b << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
return crc
def frame(seq, payload):
body = bytes([seq, len(payload)]) + payload
c = crc16(body)
return b"\x7e" + body + bytes([c >> 8, c & 0xFF])
def send(port, path):
image = open(path, "rb").read()
with serial.Serial(port, 115200, timeout=2) as s:
seq = 0
frames = 0
for off in range(0, len(image), 64):
chunk = image[off:off + 64]
for attempt in range(5):
s.write(frame(seq, chunk))
if s.read(1) == b"\x06":
break
else:
raise RuntimeError(f"frame {seq} failed")
seq = (seq + 1) & 0xFF
frames += 1
s.write(frame(seq, b""))
assert s.read(1) == b"\x06"
print(f"sent {len(image)} bytes in {frames} frames")
send(sys.argv[1], sys.argv[2])For a 49,152-byte image file (the 512-byte header plus 48,640 bytes of application) the host prints the following. The frame count is the image size divided by 64, and the sequence number on the wire wraps at 256 while the script counts frames in a separate integer:
sent 49152 bytes in 768 framesWriting flash inside the bootloader
The flash driver is the one component the update path depends on completely. The key rules are covered in the HAL flash posts of this cluster, so here is the short list a bootloader must follow:
Erase only the application sectors, never the bootloader or the boot info sector. Define the erase list as a named constant, and have a unit test that checks it against the layout table.
Program in the unit the voltage range allows. At 2.7 to 3.6 V the F4 programs 32-bit words, so buffer to a multiple of 4 bytes and pad the tail with
0xFF.Read back and verify. After the last frame, recompute the CRC of the written image before declaring success.
Refresh the watchdog during long erases. An erase of a 128 KB sector takes a considerable fraction of a second, and the bootloader should either run with the watchdog off or feed it between sectors.
Erasing the whole application region before the first byte arrives has a property worth naming: it makes the device unbootable until the update completes. That is acceptable for a bench bootloader, and unacceptable for a fleet over a flaky link. The next sections are about the designs that avoid it.
Choosing the transport
The framed UART protocol above is a teaching tool, and the transport you ship depends on the product. A few considerations decide it.
USB is the friendliest for users, because a device that appears as a mass storage drive or implements the standard DFU class needs no driver and no special tool. The cost is a USB stack in the bootloader, which is the largest single contributor to bootloader size, so on small parts teams often put USB DFU in a separate stage or rely on the vendor ROM for it. CAN and RS-485 buses suit machinery, where a gateway can update many nodes at once, and the main design problem is arbitration: only one node should be erasing at a time, and the bus must stay usable for the rest of the system while it happens. Bluetooth Low Energy updates go through a phone, which makes the slow link and the frequent disconnects the normal case, so resumable transfers and small chunk sizes matter more than raw speed. Wi-Fi and Ethernet updates use ordinary HTTPS, and the open question there is whether the bootloader speaks the network at all or whether the application downloads into the idle slot and the bootloader only installs.
That last question has a strong default. Keep the network stack in the application, where it can be updated and where a bug is recoverable, and keep the bootloader transport-free except for a minimal wired fallback. The application downloads and verifies the new image, writes it to the update slot, sets the "pending" flag and resets. The bootloader then does the one thing only it can do safely: install and start the image. A small wired recovery path, a UART or USB DFU, stays in the bootloader for the day the application cannot start.
Update strategies that survive power loss
Update strategies that survive power loss
If a device loses power halfway through an in-place update, the application is gone and the only thing left is the bootloader's ability to take another download. For a device with a reliable wired connection to a technician, that may be enough. For a remote device, it is not. Three strategies avoid the dead window, and the A/B versus swap post in this cluster compares them in detail. In summary:
| Strategy | Flash needed | Recovery from a failed update | Cost |
|---|---|---|---|
| In-place | One slot | Re-download over the same link | Cheapest, device unusable during update |
| A/B slots | Two slots | Boot the old slot | Half the flash is a spare copy, firmware needs to run from either slot |
| Swap with scratch | Two slots and a scratch area | Swap back | More flash writes, a more complex bootloader |
A/B slots
In an A/B design the device holds two complete application slots. The running application downloads the new image into the idle slot while it keeps running, verifies it, and then tells the bootloader to try it. The old slot is untouched until the new one has proven itself.
There are two ways to make an image run from either slot. One is to link two builds, one for each address, and deliver the right one. The other is a hardware bank swap, which some dual-bank parts provide, so that both slots appear at the same address. The dual-bank post in this cluster explains the swap. Without hardware support, you either ship two builds or write the application as position-independent code, which is awkward on Cortex-M and costs code size.
Swap with a scratch area
A swap design keeps a primary slot where the application always runs, a secondary slot where updates land, and a small scratch area. After a verified download, the bootloader swaps the two slots sector by sector through the scratch area, using a small log in flash to remember its progress. If power fails mid-swap, the next boot reads the log and continues. This is the approach MCUboot uses in its default swap mode, and it lets the same binary, linked once for the primary address, always run. The price is more erases, and the application slots must be the same size.
Confirm and roll back
Whichever layout you choose, a new image should not become permanent merely because it was installed. The reliable pattern is test, then confirm:
The bootloader installs the new image and marks it as pending, a trial boot.
The new image starts. It must run its own checks (it can reach the network, its sensors respond) and then explicitly mark itself confirmed.
If it crashes, hangs and trips the watchdog, or simply never confirms, the bootloader sees a pending image on the next reset and reverts to the previous one.
The bootloader needs a counter or flag in the boot info sector for this, and the application needs a one-line call to confirm. That tiny contract is what protects a fleet from a firmware that updates cleanly and then cannot connect to the network, which is a depressingly common bug.
OTA: bringing the image to the device
Once the install machinery is solid, over-the-air delivery is a download problem. The device, running its normal application, asks a server whether a newer version exists, downloads the image in pieces, and writes each piece into the update slot. A handful of design choices decide how well it behaves in the field.
Pull, not push
Let the device poll for updates on its own schedule, with a random delay so that ten thousand devices do not all connect at the same second after a release. A device behind a firewall cannot accept a connection from a server, and polling over HTTPS works through almost every network. The ESP32 post in this cluster shows esp_https_ota doing exactly that.
Resumable downloads
A cellular link drops. A battery sags. Download in chunks with HTTP range requests, store the progress, and resume where you stopped. If the image header includes the total length and the hash, the device can tell when it has everything and whether it is correct before it commits to a reboot.
Staged rollout
Do not update every device at once. Release to a small percentage, watch the confirmation rate and the crash reports, and widen the rollout when the numbers hold. This costs a few lines on the server and has saved more products than any amount of testing, because it limits the damage of a bug that only appears on hardware you do not have on the bench.
Smaller downloads
A full image of a few hundred kilobytes costs money over a cellular link. Delta updates send only the difference between two versions, which the device applies to the old image to produce the new one. They save bandwidth and cost implementation complexity: the device must hold the exact old image the delta was computed against, and a corrupted old image produces a corrupted new one. The delta post in this cluster covers the trade-offs. Compression is an easier first step, if you have the RAM for a decompressor.
Security: signing, secure boot and anti-rollback
A bootloader that accepts any image with a correct CRC lets anyone who can reach the update path run their code on your device. Three mechanisms close that, and each builds on the previous one.
Signed images
A digital signature binds an image to a private key that only you hold. The device stores the matching public key and verifies the signature before it will boot or install an image. Ed25519 is a good fit for microcontrollers: small keys, 64-byte signatures, and fast verification. ECDSA with the P-256 curve is another common choice, with hardware accelerators on many parts. The signing post in this cluster shows the verification code.
The signature covers the header and the image, so the version and length cannot be changed after signing. The private key lives on a build server or a hardware security module, never in the firmware repository.
Secure boot and the chain of trust
Verification at install time is not enough, because an attacker with physical access could write flash directly. Secure boot verifies the signature at every boot, before the application runs. The bootloader checks the application, so the question becomes who checks the bootloader. The answer is a chain of trust anchored in something that cannot be changed: a boot ROM in the chip, a lock on the bootloader sectors using option-byte write protection, or a hardware root of trust as on the ESP32 and the newer STM32 secure-boot families. The chain of trust post in this cluster covers the design.
Anti-rollback
A signed old image is still a validly signed image. If version 1.0 had a security hole that version 1.1 fixed, an attacker can reinstall version 1.0 and use it. Anti-rollback prevents that by keeping a monotonic security counter in a place that cannot be decreased, such as one-time-programmable fuses, and refusing any image whose version is lower. Use it carefully: it blocks your own legitimate downgrades too, so decide which version numbers count and what recovery you offer.
Protect the keys and the debug port
Signature checking is worthless if the public key can be replaced or the device can be reprogrammed through the debug port. Use read-out protection to block debug access to the flash, and write-protect the bootloader sectors, as the RDP and option-byte posts in this cluster describe. For confidentiality of the firmware itself, encrypt the image in transit and, where the part supports it, in storage.
Using an existing bootloader
You rarely need to write the whole thing. Mature, tested options exist and are worth considering first.
MCUboot is an open-source secure bootloader, originally from the Mynewt project, used by Zephyr and by many vendor SDKs. It supports image signing, swap and overwrite update modes, rollback and a defined image header, and it runs on dozens of Cortex-M parts. The MCUboot post in this cluster builds a secure-boot setup with it.
Vendor bootloaders, such as ST's STM32 Secure Boot and Secure Firmware Update (SBSFU) packages, and the bootloaders in Nordic's nRF Connect SDK, integrate with the vendor's hardware security features.
Optiboot on AVR and the UF2 bootloader family on many Cortex-M boards give simple, serial or drag-and-drop updates, suitable for development and hobby products.
Writing your own makes sense when you have hard constraints, such as very little flash, a proprietary transport, or a regulatory reason to keep the code small enough to audit. Even then, read the design of MCUboot first, since it encodes years of lessons about power-fail safety.
Testing a bootloader
Because a bootloader failure bricks devices, test it harder than anything else you ship.
Power-cut testing. Cut power at random points during an update, hundreds of times, with a controlled supply relay, and verify the device always recovers to either the old or the new image.
Corrupted images. Flip a bit in the payload, truncate the file, damage the header, send an image bigger than the slot. Each must be rejected cleanly.
Wrong-address images. Build the application for the wrong link address and confirm the validation, not a hard fault, is what stops it.
Reset storms. Reset the device in a loop during boot and during the update.
Full-flash tests. Update with an image that fills the slot exactly, and one byte larger.
Version rules. Test downgrade attempts and equal versions against your policy.
A simulator for the flash driver on the host makes most of these repeatable: it records every flash operation, injects a power cut after N operations, and runs the boot logic again on the resulting flash image. The host-testing cluster on this site develops that technique.
Debugging a bootloader that does not work
Symptoms usually point to one of a small set of causes. A short checklist:
Nothing happens at all. The bootloader itself is not starting. Check that its vector table is at
0x08000000and thatBOOT0is low. Run it under the debugger first, before it has to jump anywhere.It jumps and the application crashes immediately. Compare the application's link address with
APP_VECTORS, and checkVECT_TAB_OFFSET. Print the stack pointer and reset handler values the bootloader read.The CRC never matches. Make the bootloader and the host script agree on the CRC variant: reflected or not, initial value, final XOR. Compare a known string,
123456789, which should give0xCBF43926for the zlib variant.It works from the programmer and fails after an update. The update path wrote the data in a different place, or did not erase before programming. Read the flash back through the debugger and compare it with the image file.
It works for months and then one device fails. Suspect a power cut during an update and a missing recovery path, then check watchdog, brown-out and supply behavior on that unit.
Printing a few lines on a UART from the bootloader costs a hundred bytes of code and saves days. Keep that log in release builds.
A complete design checklist
Before shipping a bootloader and OTA scheme, confirm each item below.
The flash layout has a bootloader, boot info, and one or two application slots, aligned on sector boundaries.
The application is linked for its slot address and sets
VTORto match.The image header carries a magic number, a version, a length and a hash, and is written last.
The bootloader validates the whole image, not only the header, before it jumps.
The hand-over leaves no timer, interrupt or clock configuration behind.
A failed or interrupted update always leaves the device able to recover.
New images boot as pending and must confirm themselves, with a rollback path.
Images are signed, the public key is protected, and rollback of old versions is controlled.
Read-out protection and write protection cover the bootloader and the keys.
Power-cut and corruption tests run in the build pipeline.
A staged rollout and a way to observe results are in place before the first release.


