atmega128 bootloader程序
时间: 2023-09-09 10:10:42 浏览: 110
atmega128 bootloader
ATmega128是AVR系列的微处理器,它可以使用Bootloader程序进行固件更新。Bootloader程序是一种特殊的程序,允许用户通过串口(或其他接口)将新的固件上传到芯片中,而无需使用专用的编程器。
以下是使用AVR-GCC编译器和AVRDUDE工具链编写的ATmega128 Bootloader程序示例:
```c
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/boot.h>
#define F_CPU 16000000UL
#define BAUD 19200
#define MYUBRR F_CPU/16/BAUD-1
void USART_Init(unsigned int ubrr) {
UBRR0H = (unsigned char)(ubrr>>8);
UBRR0L = (unsigned char)ubrr;
UCSR0B = (1<<TXEN0)|(1<<RXEN0);
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
}
void USART_Transmit(unsigned char data) {
while (!(UCSR0A & (1<<UDRE0)));
UDR0 = data;
}
unsigned char USART_Receive(void) {
while (!(UCSR0A & (1<<RXC0)));
return UDR0;
}
void USART_putstring(char* string) {
while (*string) {
USART_Transmit(*string++);
}
}
void bootloader() {
void (*app_start)(void) = 0x0000;
unsigned char ch;
unsigned char *bufptr;
unsigned int address = 0;
unsigned char pagebuffer[SPM_PAGESIZE];
USART_Init(MYUBRR);
USART_putstring("Bootloader started!\n");
do {
ch = USART_Receive();
switch (ch) {
case 'a': // Get bootloader version
USART_putstring("Bootloader version 1.0\n");
break;
case 'b': // Read byte from flash
address = USART_Receive() | (USART_Receive()<<8);
USART_Transmit(pgm_read_byte_near(address));
break;
case 'c': // Write byte to flash
address = USART_Receive() | (USART_Receive()<<8);
bufptr = pagebuffer;
*bufptr++ = USART_Receive();
boot_page_erase(address);
boot_spm_busy_wait();
boot_page_fill(address, *pagebuffer);
boot_page_write(address);
boot_spm_busy_wait();
USART_putstring("Byte written!\n");
break;
case 'd': // Jump to application
USART_putstring("Jumping to application...\n");
app_start();
break;
default:
break;
}
} while (1);
}
int main(void) {
bootloader();
return 0;
}
```
这个示例程序实现了一个简单的Bootloader,通过串口与用户进行交互,实现读取、写入和跳转到应用程序的功能。在这个示例中,我们使用AVRDUDE工具将新的固件上传到芯片中。上传的固件应该是一个可执行程序,它将被存储在ATmega128芯片的Flash存储器中,并在跳转到应用程序之前被验证。
请注意,这只是一个简单的示例程序,实际的Bootloader程序可能需要更复杂的功能和更多的错误处理。
阅读全文