The user asked to build a bootloader in C for an AVR microcontroller, mentioning code and explanation. I need to clarify specifics like the bootloader type, MCU model (like ATmega328P), and communication interface (e.g., UART). Since the user didn't specify, I’ll choose a common option like ATmega328P, often used with Arduino Uno, and create a generic minimal UART-based bootloader.
I should touch on linker sections, relevant fuses, watchdog reset, vital instructions, and self-programming, ensuring the explanation remains concise yet informative. I’ll provide a sample bootloader and notes on adaptations.Planning bootloader specifics
I need to start by choosing the MCU, like the ATmega328P, and mention how to adapt the bootloader for other models. Next, I’ll outline the high-level design, including the memory map, boot reset conditions, BOOTSZ fuse settings, and communication protocol.
I'll provide C code with embedded assembly for certain instructions using avr-libc macros. A simple serial protocol, like Intel HEX, is preferable, but I’ll keep it basic for demonstration. The bootloader needs to fit within 2KB, placing it at the higher memory section, requiring attention to fuses.Clarifying bootloader size
So, the ATmega328P has a maximum flash memory of 32KB (or 16K words), and the bootloader size can be 256, 512, 1024, or 2048 words. The boot section size is specified in words. If I’m designing a 2KB bootloader, it will start at address 0x7800 in flash.
I should make sure to compile with special linker options, such as -Wl,--section-start=.text=0x7E00. The addresses I mention need careful disclaimers regarding words versus bytes. Links to proper sections will help clarify this further!Setting Boot Size Fuses
I need to set the BOOTSZ fuses for the ATmega328P correctly. For a 2KB bootloader, I think I should set BOOTSZ1 to 0 and BOOTSZ0 to 1. According to the ATmega328P datasheet, the boot size mapping indicates that 00 corresponds to 8KB (4096 words), 01 to 4KB (2048 words), 10 to 2KB (1024 words), and 11 to 1KB (512 words).
So, for my bootloader area, I'll set the fuses to allow for 2KB starting at address 0x7800, and it's crucial to check the datasheet for the specific fuse bits. I'll also note that the BOOTRST fuse will help in setting the Boot Reset vector.Designing Bootloader Functionality
I need to outline the hardware setup, like using a microcontroller with UART0 at 115200 baud. The bootloader's tasks include checking conditions on reset, initializing UART, and implementing a protocol for flash programming using embedded commands. I'll use avr-libc’s functions for simplicity and define a buffer size based on the SPM_PAGESIZE.
For the ATmega328P, SPM_PAGESIZE is crucial, as it's 256 bytes, so I’ll ensure my code reflects this. I’ll set up a simple command protocol for pages in the bootloader, ensuring commands like SYNC and WRITE are handled correctly, while also making sure not to write to the bootloader section itself.Implementing Bootloader Functions
I'm outlining a bootloader code structure for the user. I'll implement the main loop to check for the SYNC 'U' character and handle timeouts effectively. A basic loop will create the delay for detecting the handshake while remaining efficient.
Next, I plan to define command constants like CMD_SYNC, CMD_WRITE_PAGE, and CMD_START_APP for a streamlined protocol. The bootloader will run from a specified section and handle flash programming operations safely.
It’s essential to ensure that the bootloader does not modify its own section during operations, which I will highlight in the code documentation.Clarifying Bootloader Setup
I'm rethinking the bootloader's setup for ensuring it runs correctly. I believe we should wrap the program_page function with cli() to handle potential concurrency, even though interrupts are disabled by default.
Next, I plan to compile with specific parameters to ensure the .text section starts at 0x7800 without needing vector tables if we don't use interrupts. The key is that when the BootRST fuse is set, the PC resets to the bootloader start, making the entry point critical.
So, it's about getting this linking right while considering where the vector tables are placed relative to the bootloader.Organizing Bootloader Sections
I’m realizing that while the .vectors section remains at 0, our .text starts at 0x7800, meaning the initialization code will execute properly. Even though we won't use those 0xFF values, I still need to confirm whether to include -nostartfiles. The CPU will initiate at 0x7800, and since the standard startup code begins at 0, I have to ensure that the vector and text sections are aligned correctly.
Compiling with -Wl,--section-start for both sections should help clarify where the program will start without issues. This is getting complex!Finalizing Bootloader Code
Alright, I’m working on the bootloader code. The .vectors section will start at BootStart (0x7800), and the application must still maintain its reset vector at 0. BootRST takes care of routing resets to the bootloader, but we need to ensure that the vector table for the app is still accessible at 0.
I'm including key functions for writing and erasing flash memory, while also remembering to disable the watchdog timer to prevent unwanted resets. I’ll provide a concise outline and code for a simple UART bootloader for the ATmega328P, ensuring the explanation remains straightforward!Clarifying Bootloader Setup
I’m outlining how to set up the bootloader. Typically, the C start-up code initializes the stack pointer (SP) upon reset, but since we're skipping that, I’ll set SP explicitly at RAMEND for clarity.
In the main function, I’ll disable the watchdog timer right at the start. I have to ensure no functions from standard libraries that rely on interrupts or dynamic memory are called.
I'll include the necessary compile commands with good comments, and I plan to guide on fuse settings without giving numerical specifics, just to keep it safe. Let’s start writing the code!Crafting Bootloader Code
I’m composing the full code for a minimal UART bootloader meant for the ATmega328P. This code will facilitate flash page programming and communicate over UART0 at a baud rate of 115200.
The protocol is straightforward, awaiting a synchronization byte 'U'. If it receives 'U', it responds with 'K' and accepts commands to write pages or jump to the application. I've also included the code structure for UART communication and flash programming functions.
Now, I need to outline the build instructions, including compile flags and fuse settings. Let's compile and ensure everything aligns smoothly!Building the Bootloader
To compile the bootloader, use the following command:
Set the fuses appropriately for boot size and reset vectors. Build your application to start below the bootloader, ensuring proper UART communication at 115200 baud for commands. You can customize for other AVR chips, adjusting as necessary. Below is a complete, minimal UART bootloader in C for an AVR microcontroller, specifically an ATmega328P (e.g. Arduino Uno). It:
Lives in the top 2 KB of flash (bootloader section).
Uses UART0 at 115200 baud.
Programs flash one page at a time.
Jumps to the application at 0x0000 if no PC connects within ~1 s.
You can adapt it to other AVRs by changing F_CPU, the bootloader start address, and fuse settings.
1. Bootloader C Code (ATmega328P, 16 MHz, UART0 @ 115200)
Save as bootloader.c:
c
Notes:
SPM_PAGESIZE is defined by <avr/boot.h> for your MCU; it’s the flash page size in bytes.
On ATmega328P it matches the hardware page size automatically; you don't need to hard-code it.
2. Building and Flashing the Bootloader
Assuming avr-gcc and avr-objcopy and avrdude are installed, and target is ATmega328P @ 16 MHz:
-Wl,--section-start=.text=0x7800 places the .text output section (which includes the vector table) at byte address 0x7800, the start of a 2 KB boot section for a 32 KB flash.
Set BOOTSZ and BOOTRST fuses appropriately for that MCU.
If you want, I can help you tailor this to a specific AVR (e.g. ATmega32, ATmega128, ATtiny series) and sketch a small Python host tool to drive the protocol.
/* bootloader.c
*
* Minimal UART bootloader for ATmega328P
* - Flash page programming using avr-libc <avr/boot.h>
* - UART0 at 115200 8N1
* - Boot section size = 2 KB -> start address 0x7800
*
* Protocol (very simple):
* After reset, bootloader waits ~1 s for the byte 'U' (0x55).
* If not received, it jumps to the application at 0x0000.
*
* Once synchronized:
* PC sends: 'U'
* MCU replies: 'K'
*
* Command 'W' (write one page):
* PC sends:
* 'W'
* page_index_hi
* page_index_lo
* SPM_PAGESIZE bytes of data for that page
* MCU:
* programs the page
* replies 'K' on success
*
* Command 'J' (jump to application):
* PC sends:
* 'J'
* MCU:
* replies 'K'
* jumps to application at 0x0000
*/
#include <avr/io.h>
#include <avr/boot.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/wdt.h>
#define F_CPU 16000000UL
#define BAUD 115200UL
#define UBRR_VALUE ((F_CPU / (16UL * BAUD)) - 1)
/* For ATmega328P:
* Flash = 32 KB = 0x8000 bytes
* 2 KB bootloader -> boot section starts at 0x8000 - 0x0800 = 0x7800
*/
#define BOOTLOADER_START 0x7800UL
#define APP_FLASH_END (BOOTLOADER_START - 1)
/* Protocol bytes */
#define CMD_SYNC 'U'
#define REPLY_OK 'K'
#define CMD_WRITE_PAGE 'W'
#define CMD_JUMP_APP 'J'
/* -------------------------------------------------------------------------- */
/* UART */
/* -------------------------------------------------------------------------- */
static void uart_init(void)
{
/* Set baud rate */
UBRR0H = (uint8_t)(UBRR_VALUE >> 8);
UBRR0L = (uint8_t)(UBRR_VALUE & 0xFF);
/* 8N1, asynchronous */
UCSR0A = 0;
UCSR0B = (1 << RXEN0) | (1 << TXEN0);
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
}
static void uart_putc(uint8_t c)
{
while (!(UCSR0A & (1 << UDRE0))) {
/* wait */
}
UDR0 = c;
}
static uint8_t uart_getc(void)
{
while (!(UCSR0A & (1 << RXC0))) {
/* wait */
}
return UDR0;
}
/* Return -1 on timeout (approx. timeout_ms milliseconds) */
static int16_t uart_getc_timeout(uint16_t timeout_ms)
{
/* Crude software timeout; good enough for bootloader use */
while (timeout_ms--) {
for (uint16_t i = 0; i < (F_CPU / 4000UL); i++) {
if (UCSR0A & (1 << RXC0)) {
return UDR0;
}
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* Flash programming */
/* -------------------------------------------------------------------------- */
/* Program one flash page from RAM buffer.
* page_index: 0 for first application page, 1 for second, etc.
* buf: must contain SPM_PAGESIZE bytes.
*/
static void program_page(uint16_t page_index, uint8_t *buf)
{
uint16_t i;
uint32_t address = (uint32_t)page_index * SPM_PAGESIZE;
/* Prevent overwriting the bootloader area. */
if (address + SPM_PAGESIZE > APP_FLASH_END) {
return;
}
/* Erase page */
boot_page_erase(address);
boot_spm_busy_wait();
/* Fill temporary page buffer */
for (i = 0; i < SPM_PAGESIZE; i += 2) {
uint16_t w = buf[i] | ((uint16_t)buf[i + 1] << 8);
boot_page_fill(address + i, w);
}
/* Write page */
boot_page_write(address);
boot_spm_busy_wait();
/* Re-enable RWW section for reading */
boot_rww_enable();
}
/* -------------------------------------------------------------------------- */
/* Jump to application */
/* -------------------------------------------------------------------------- */
static void jump_to_application(void) __attribute__((noreturn));
static void jump_to_application(void)
{
cli();
wdt_disable();
/* Jump to application reset vector at 0x0000. */
void (*app_start)(void) = 0x0000;
app_start();
for (;;) {
/* never returns */
}
}
/* -------------------------------------------------------------------------- */
/* Early init: disable watchdog if app left it running */
/* -------------------------------------------------------------------------- */
/* Run very early (before main) */
void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
void wdt_init(void)
{
MCUSR = 0;
wdt_disable();
}
/* -------------------------------------------------------------------------- */
/* Main bootloader logic */
/* -------------------------------------------------------------------------- */
int main(void)
{
uint8_t page_buffer[SPM_PAGESIZE];
int16_t ch;
uart_init();
/* Wait ~1 second for sync character; otherwise start application. */
ch = uart_getc_timeout(1000);
if (ch != CMD_SYNC) {
jump_to_application();
}
/* Acknowledge sync */
uart_putc(REPLY_OK);
for (;;) {
ch = uart_getc();
if (ch == CMD_WRITE_PAGE) {
uint16_t page_index;
uint8_t *p = page_buffer;
/* Receive page index (big endian) */
uint8_t hi = uart_getc();
uint8_t lo = uart_getc();
page_index = ((uint16_t)hi << 8) | lo;
/* Receive exactly one page of data */
for (uint16_t i = 0; i < SPM_PAGESIZE; i++) {
*p++ = uart_getc();
}
program_page(page_index, page_buffer);
uart_putc(REPLY_OK);
}
else if (ch == CMD_JUMP_APP) {
uart_putc(REPLY_OK);
jump_to_application();
}
else if (ch == CMD_SYNC) {
/* Resync request */
uart_putc(REPLY_OK);
}
else {
/* Ignore unknown commands */
}
}
}