/*
* Minimal AVR Bootloader in C for ATmega328P (e.g., Arduino Uno).
* Features:
* - UART bootloader at 115200 baud (8N1).
* - Enter bootloader by sending 0x1B 0x1B 0x1B (ESC ESC ESC) within ~5 seconds after reset/power-on.
* - Bootloader replies with "BOOT".
* - Host then sends uint16_t length (little-endian), followed by exactly 'length' bytes of application firmware (raw binary).
* - Programs flash starting at address 0x0000, handling partial last page (pads with 0xFF).
* - After programming, sends "OK" and jumps to application.
* - 1KB bootloader size (fits in boot section).
* - No EEPROM support, no CRC (add if needed for robustness).
*
* Compile:
* avr-gcc -std=gnu99 -Wall -Os -mmcu=atmega328p -DF_CPU=16000000UL -DBAUD=115200 \
* -Wl,--section-start=.text=0x7e00 -ffunction-sections -fdata-sections \
* -fno-inline-small-functions -nostartfiles -Wl,--relax bootloader.c -o bootloader.elf
*
* Generate HEX:
* avr-objcopy -O ihex -R .eeprom bootloader.elf bootloader.hex
*
* Flash bootloader (e.g., with USBasp):
* avrdude -c usbasp -p m328p -U flash:w:bootloader.hex:i \
* -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m -U lock:w:0x3F:m
*
* Fuses explanation:
* - BOOTRST=1, BOOTSZ0=1, BOOTSZ1=0 → 1024-byte bootloader starting at 0x7E00.
* - After flashing, lock bits protect bootloader (0x3F = BLB12=1, BLB11=1).
*
* Usage with Python uploader (requires pyserial):
* import serial
* ser = serial.Serial('COM3', 115200, timeout=1) # Adjust port
* ser.write(b'\x1B\x1B\x1B')
* resp = ser.read(4)
* if resp == b'BOOT':
* with open('app.bin', 'rb') as f: # Raw binary: avr-objcopy -O binary app.elf app.bin
* data = f.read()
* assert len(data) <= 0x7E00 # Don't overwrite bootloader!
* ser.write(len(data).to_bytes(2, 'little') + data)
* ok = ser.read(2)
* print('OK' if ok == b'OK' else 'FAIL')
* ser.close()
*/
#include <avr/io.h>
#include <avr/boot.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <util/setbaud.h>
#define BAUD 115200UL
#define ENTER_SEQ 0x1B // ESC
#define SPM_PAGESIZE 256
#define BOOT_TIMEOUT_MS 5000
#define RX_TIMEOUT_MS 100
// UART functions
static void uart_init(void) {
UBRR0H = UBRR_VALUE >> 8;
UBRR0L = UBRR_VALUE;
#if USE_2X
UCSR0A |= _BV(U2X0);
#endif
UCSR0B = _BV(RXEN0) | _BV(TXEN0);
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
}
static void uart_putchar(char c) {
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
}
static uint8_t uart_get(uint8_t *c, uint16_t timeout_ms) {
uint16_t t = 0;
while (!(UCSR0A & _BV(RXC0))) {
_delay_ms(1);
if (++t >= timeout_ms) return 0;
}
*c = UDR0;
return 1;
}
// Detect enter sequence: 3 consecutive ENTER_SEQ
static uint8_t boot_enter_detect(void) {
uint8_t count = 0;
uint16_t timeout_cnt = 0;
while (timeout_cnt < (BOOT_TIMEOUT_MS / 10)) {
if (UCSR0A & _BV(RXC0)) {
uint8_t byte;
loop_until_bit_is_set(UCSR0A, RXC0);
byte = UDR0;
if (byte == ENTER_SEQ) {
if (++count >= 3) return 1;
} else {
count = 0;
}
}
_delay_ms(10);
timeout_cnt++;
}
return 0;
}
// Erase and write one flash page
static void flash_write_page(uint16_t page_addr, uint8_t *buf) {
boot_page_erase(page_addr);
boot_spm_busy_wait();
for (uint16_t i = 0; i < SPM_PAGESIZE; i += 2) {
uint16_t word = ((uint16_t)buf[i + 1] << 8) | buf[i];
boot_page_fill(page_addr + i, word);
}
boot_page_write(page_addr);
boot_spm_busy_wait();
}
// Jump to application (relocate vectors to 0x0000)
static void jump_to_app(void) {
// Relocate interrupt vectors
MCUCR = _BV(IVCE);
MCUCR = 0;
asm("jmp 0x0000");
}
int main(void) {
uart_init();
// Detect bootloader enter
if (boot_enter_detect()) {
// Reply "BOOT"
uart_putchar('B');
uart_putchar('O');
uart_putchar('O');
uart_putchar('T');
// Receive length (uint16_t LE)
uint8_t len_low, len_high;
if (!uart_get(&len_low, RX_TIMEOUT_MS) || !uart_get(&len_high, RX_TIMEOUT_MS)) {
jump_to_app();
}
uint16_t length = ((uint16_t)len_high << 8) | len_low;
if (length > 0x7E00 || length == 0) { // Sanity: don't overwrite bootloader
jump_to_app();
}
uint8_t pagebuf[SPM_PAGESIZE];
uint16_t addr = 0;
while (addr < length) {
uint16_t page_addr = addr & ~(SPM_PAGESIZE - 1);
uint16_t bytes_in_page = SPM_PAGESIZE;
if (addr + bytes_in_page > length) {
bytes_in_page = length - addr;
}
// Receive data for this page
for (uint16_t i = 0; i < bytes_in_page; i++) {
if (!uart_get(&pagebuf[i], RX_TIMEOUT_MS)) {
jump_to_app(); // Timeout/error: abort
}
}
// Pad remainder with 0xFF
for (uint16_t i = bytes_in_page; i < SPM_PAGESIZE; i++) {
pagebuf[i] = 0xFF;
}
// Program page
flash_write_page(page_addr, pagebuf);
addr += SPM_PAGESIZE;
}
// Success: reply "OK"
uart_putchar('O');
uart_putchar('K');
// Jump to app
jump_to_app();
}
// Timeout: jump to app
jump_to_app();
return 0; // Unreachable
}
Additional Notes
- Security: No authentication or encryption—suitable for development only. Add HMAC/CRC if needed.
- Verification: Optional—add
if (pgm_read_byte_near(page_addr) != pagebuf[0]) after boot_spm_busy_wait() and abort on mismatch.
- RAM Usage: ~300 bytes (fits in 2KB).
- Size: Compiles to ~400 bytes.
- Customization: Adjust
BAUD, ENTER_SEQ, timeouts, or target MCU (change mmcu, SPM_PAGESIZE, app size check).
- Reset Behavior: After programming, app starts immediately. To re-enter bootloader, reset and send sequence quickly.
- Troubleshooting: Ensure F_CPU matches crystal (16MHz for Arduino). Use
avrdude -c arduino -p m328p -P /dev/ttyUSB0 -U flash:r:dump.hex:i to verify.
This is a fully functional, minimal bootloader ready to build and use!