注明:本程序选用官方的boot库函数进行试验,开发环境是 atmelstudio6( avrstudio6 )。
官方供给了bootloader相关的写入擦除函数。
主函数如下:
int main(void)
{
USARTInit(115200);
for (int i=0;i<256;i++)
{//此处数据均为00010203方式
if ((i&3)==0)
{
databuff.databuff8[i]=0;
}
else if ((i&3)==1)
{
databuff.databuff8[i]=1;
}
else if ((i&3)==2)
{
databuff.databuff8[i]=2;
}
else if ((i&3)==3)
{
databuff.databuff8[i]=3;
}
}
address = 0;
boot_write_one_page();
for (int i=0;i<256;i++)
{//此处数据均为00ff00ff方式
if (i&1)
{
databuff.databuff8[i]=0XFF;
}
else
{
databuff.databuff8[i]=0;
}
}
address += 256;
boot_write_one_page();
address = 0;
boot_check_flash();
address += 256;
boot_check_flash();
while(1);
}
下面是写入一页的程序:
void boot_write_one_page(void)
{
int i;
DataUnionByte TempData;
boot_page_erase(address);// 擦除一页
boot_spm_busy_wait();// 等候擦除完结
for (i=0;i
{
TempData.databuff8[0]=databuff.databuff8[i];
TempData.databuff8[1]=databuff.databuff8[i+1];
boot_page_fill_safe(i,TempData.databuff16);
}
boot_page_write_safe(address);
boot_rww_enable_safe();
}
unsigned int read_program_memory (unsigned int adr ,unsigned char cmd)
{
asm(“movw r30, r24”);//仿制地址到z寄存器
asm(“SBRC r22, 0″);
asm(“STS 0x37, r22″);//r22->0x37(SPMCR)
asm(“LPM r24, Z+”);
asm(“LPM r25, Z”);//获取回来数据
asm(“ret”);
}
下面是对flash数据进行读取并串口打印的函数
void boot_check_flash(void)
{
DataUnionByte TempData;
for (int i=0;i<128;i+=2)
{
TempData.databuff16 = read_program_memory(address+i,0x00);
USARTTransmit(TempData.databuff8[0]);
USARTTransmit(TempData.databuff8[1]);
}
}
运转成果如下:
