Home / Learn Chip Programming / Project 8: Custom UART Bootloader
Project 8: Custom UART Bootloader
Write a tiny bootloader that receives a new firmware over UART, checks a CRC and jumps to the application.
Theory in plain words
What it is
The bootloader sits at the start of flash. It listens for a few seconds. If a PC sends an update it erases the app area, writes the packets and verifies a CRC32 before running the app.
Why we use it
Updating firmware in the field without a programmer is required in every real product. You learn flash, vector tables, jumping to code and protocol design.
How it works
Place the bootloader at 0x08000000 (8 KB), the app at 0x08002000. Set the app VTOR and stack pointer, then jump to the reset handler. Frames: START, length, address, data, CRC.
Where it is used
- IoT updates
- Factory programming
- Recovery mode in products
Equipment
You need the ST-Link once to flash the bootloader itself. After that, updates come through the USB serial adapter.
Wiring
| From | To | Note |
|---|---|---|
| Blue Pill PA9 (TX) | adapter RX | cross TX and RX |
| Blue Pill PA10 (RX) | adapter TX | use 3.3 V logic |
| GND | GND | common ground |
| PC13 LED | onboard | blink pattern shows bootloader mode |
| ST-Link SWD | SWCLK, SWDIO, GND, 3V3 | only to install the bootloader |
Live bootloader protocol simulator
Without CRC a corrupted update would brick the device. Never jump to an image that failed verification.
Code (jump to application)
#define APP_ADDR 0x08002000u
typedef void (*app_fn)(void);
static int app_valid(void) {
uint32_t sp = *(volatile uint32_t *)APP_ADDR; // first word: initial stack pointer
uint32_t rst = *(volatile uint32_t *)(APP_ADDR + 4); // second: reset handler
return (sp & 0x2FFE0000) == 0x20000000 && rst >= APP_ADDR && rst < 0x08010000;
}
static void jump_to_app(void) {
HAL_RCC_DeInit(); HAL_DeInit(); // return peripherals to reset state
SysTick->CTRL = 0; __disable_irq();
SCB->VTOR = APP_ADDR; // application owns the vector table
__set_MSP(*(volatile uint32_t *)APP_ADDR);
((app_fn)*(volatile uint32_t *)(APP_ADDR + 4))();
}
int main(void) {
hw_init();
if (wait_for_host(2000)) update_firmware(); // receive frames, erase, write, verify crc
if (app_valid()) jump_to_app();
for (;;) blink_error(); // nothing to run
}- Define the flash map: bootloader 8 KB, application from 0x08002000. Set the linker script FLASH ORIGIN of the app accordingly.
- Write the app first: a blinking LED with VTOR_TABLE_OFFSET = 0x2000.
- Write the bootloader: jump_to_app() only. Check that the app starts.
- Add the UART protocol with ACK/NAK and per-frame CRC.
- Write a small Python script (pyserial) that sends a .bin file in frames.
Quick quiz
1. Before jumping to the app we must...
The app has its own vector table.
2. Why check CRC of the image?
A bad update must not boot.