|
本帖最后由 阿里兄 于 2020-6-1 12:00 编辑
出问题前使用的方法如下:仿真看半天也没看出问题在哪里,最后发现*pBuffer的地址是非4字节对齐,最后通过一个32位的中间变量解决了,也就是说HAL_FLASH_Program必需与写入的类型要对齐,即如果是
FLASH_TYPEPROGRAM_HALFWORD,表示写入的数的地址要2字节对齐,
FLASH_TYPEPROGRAM_WORD,表示写入的数的地址要4字节对齐,
FLASH_TYPEPROGRAM_DOUBLEWORD,表示写入的数的地址要8字节对齐。
- //pBuffer:数据存储区
- //WriteAddr:开始写入的地址(24bit)
- //NumByteToWrite:要写入的字节数(最大256),该数不应该超过该页的剩余字节数!!!
- void FLASH_Write_Page(uint8_t *pBuffer,uint32_t WriteAddr,uint16_t NumByteToWrite)
- {
- if ( (WriteAddr%FLASH_SECT_SIZE) == 0 )//如果写入地址为扇区地址
- {
- FLASH_Erase_Sector(WriteAddr);//需要先擦除扇区
- }
- HAL_FLASH_Unlock();
- __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR);
- for (int i = 0; i<NumByteToWrite; i+=4)
- {
- HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, WriteAddr, *(uint32_t*)(pBuffer+i));
- WriteAddr+=4;
- }
- HAL_FLASH_Lock();
- }
复制代码
修改后的使用方法如下:
- //pBuffer:数据存储区
- //WriteAddr:开始写入的地址(24bit)
- //NumByteToWrite:要写入的字节数(最大256),该数不应该超过该页的剩余字节数!!!
- void FLASH_Write_Page(uint8_t *pBuffer,uint32_t WriteAddr,uint16_t NumByteToWrite)
- {
- if ( (WriteAddr%FLASH_SECT_SIZE) == 0 )//如果写入地址为扇区地址
- {
- FLASH_Erase_Sector(WriteAddr);//需要先擦除扇区
- }
- HAL_FLASH_Unlock();
- __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR);
- for (int i = 0; i<NumByteToWrite; i+=4)
- {
- uint32_t data_tem;
- memcpy(&data_tem, pBuffer+i, 4);
- HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, WriteAddr, data_tem);
- WriteAddr+=4;
- }
- HAL_FLASH_Lock();
- }
复制代码
|
|