下面是Flash写N个半字的函数:
ErrorStatus Flash_User_WriteNHalfWord(uint16_t offAddress, uint16_t *buffer,uint16_t len_halfword)
{
FLASH_Status status = FLASH_COMPLETE;
uint16_t i;
EMPTYStatus Empty=EMPTY;
uint16_t pageaddr,pageoffset_half;
uint16_t flash_buf[FLASH_PAGE_HALF_SIZE];
assert_param(IS_FLASH_PROGRAM_ADDRESS(offAddress+len_halfword*2-1));
offAddress &= FLASH_ADDR_ALIGN; //half word align
pageaddr = offAddress & FLASH_PAGE_ADDR_MSK;
pageoffset_half = (offAddress & (~FLASH_PAGE_ADDR_MSK))/2;
if((offAddress+len_halfword*2-2)>=FLASH_OFFSET_END)
{
printf("\n\rFlash space is not enough!\n\r");
return ERROR;
}
Empty = Flash_Check_Empty(offAddress,len_halfword); //查要写的部分是否全为空,如果为空,后续不用擦除,否则进行整页擦除
// Flash_ReadNHalfWord(offAddress,flash_buf,len_halfword); //这里有个问题,我用这个注释掉的部分代码,而不用Flash_Check_Empty(),写操作OK
// for (i=0;i<len_halfword;i++) //用上面那个替代就会跑死
// {
// if(flash_buf[i] !=0xFFFF)
// {
// Empty = NOTEMPTY;
// break;
// }
// }
status = FLASH_WaitForLastOperation(FLASH_ER_PRG_TIMEOUT);
if(status == FLASH_COMPLETE)
FLASH_Unlock();
if(Empty == EMPTY)
{
for(i=0;i<len_halfword;i++)
FLASH_ProgramHalfWord((FLASH_BASE+offAddress+2*i),buffer[i]);
}
else
{
Flash_ReadNHalfWord(pageaddr,flash_buf,FLASH_PAGE_HALF_SIZE); //read program area data
for (i=0;i<len_halfword;i++)
flash_buf[pageoffset_half+i] = buffer[i];
FLASH_ErasePage(FLASH_BASE+pageaddr);
for (i=0;i<FLASH_PAGE_HALF_SIZE;i++)
FLASH_ProgramHalfWord((FLASH_BASE+pageaddr+2*i),flash_buf[i]);
}
status = FLASH_WaitForLastOperation(FLASH_ER_PRG_TIMEOUT);
if(status == FLASH_COMPLETE)
FLASH_Lock();
return SUCCESS;
}
|