基于C语言编写atmega128的bootloader程序
时间: 2023-08-31 15:06:15 浏览: 184
以下是一个基于 C 语言编写的 ATmega128 Bootloader 程序的示例代码:
```c
#include <avr/io.h>
#include <avr/boot.h>
#include <avr/interrupt.h>
#define BAUD 9600
#define F_CPU 8000000UL
#define UART_BAUDRATE (((F_CPU / (BAUD * 16UL))) - 1)
void uart_init(void)
{
UBRR0H = (uint8_t)(UART_BAUDRATE >> 8);
UBRR0L = (uint8_t)(UART_BAUDRATE);
UCSR0B = (1 << TXEN0) | (1 << RXEN0);
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
}
void uart_putc(uint8_t data)
{
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = data;
}
void uart_puts(char *str)
{
while (*str)
{
uart_putc(*str++);
}
}
void jump_to_app(void)
{
void (*app_start_addr)(void) = 0x0000;
app_start_addr();
}
int main(void)
{
uart_init();
sei();
uart_puts("ATmega128 Bootloader\r\n");
if (!(PINB & (1 << PINB0)))
{
uart_puts("Entering Bootloader Mode\r\n");
while (1)
{
uint8_t data = uart_getc();
if (data == 'u')
{
uart_puts("Unlocking Application\r\n");
boot_lock_bits(0x00);
}
else if (data == 'e')
{
uart_puts("Erasing Application\r\n");
boot_page_erase(0x0000);
boot_spm_busy_wait();
}
else if (data == 'w')
{
uart_puts("Writing Application\r\n");
uint16_t address = 0x0000;
uint8_t *buffer = (uint8_t *)(0x0000);
for (uint16_t i = 0; i < SPM_PAGESIZE; i += 2)
{
uint16_t data = uart_getc();
data |= uart_getc() << 8;
buffer[i] = data & 0xFF;
buffer[i + 1] = data >> 8;
}
boot_page_write(address, buffer);
boot_spm_busy_wait();
boot_rww_enable();
}
else if (data == 'j')
{
uart_puts("Jumping to Application\r\n");
jump_to_app();
}
}
}
else
{
jump_to_app();
}
return 0;
}
```
这个程序基于 UART 模块实现 ATmega128 的 Bootloader 功能。当启动程序时,它会检测 PINB0 引脚是否为低电平,如果是,则进入 Bootloader 模式,等待来自串口的指令,以擦除、编程和解锁 Flash 存储器。如果 PINB0 引脚为高电平,则跳转到应用程序地址开始执行应用程序。
阅读全文