这是我在这里发表的第一篇文章,如果格式错误或遗漏,请对不起。根据我们大学here和here的建议,我成功地编写和阅读了STM32F4 Discovery的闪存(两篇文章都用同样的方式解释):
__attribute__((__section__(".user_data"))) const char userConfig[64];
[...]
void Write_Flash(uint8_t data)
{
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
FLASH_Erase_Sector(FLASH_SECTOR_6, VOLTAGE_RANGE_3);
HAL_FLASH_Program(TYPEPROGRAM_WORD, &userConfig[0], data);
HAL_FLASH_Lock();
}
[...]
dataSize=(sizeof dataBuffer) / (sizeof *dataBuffer);
for (i=0;i<dataSize;i++) {
dataBuffer[i]=i+1;
}
Write_Flash(dataBuffer[0]);
上面的代码工作正常,并将1写入userConfig[0]
。从这一点来说,我有以下问题。我只能在闪存中写一个字节,不知道如何写更多。我试图更改HAL_FLASH_Program(TYPEPROGRAM_WORD, &userConfig[0], data);
的地址,但仅适用于&userConfig[0]
这是我尝试写几个字节但没有成功:
__attribute__((__section__(".user_data"))) const char userConfig[64];
[...]
void Write_Flash(uint8_t data, uint8_t i)
{
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
FLASH_Erase_Sector(FLASH_SECTOR_6, VOLTAGE_RANGE_3);
HAL_FLASH_Program(TYPEPROGRAM_WORD, &userConfig[i], data);
HAL_FLASH_Lock();
}
[...]
dataSize=(sizeof dataBuffer) / (sizeof *dataBuffer);
for (i=0;i<dataSize;i++) {
dataBuffer[i]=i+1;
Write_Flash(dataBuffer[i],i);
}
提前感谢您的帮助。
答案 0 :(得分:1)
感谢@phyloflash我得到了答案。当您调用HAL_FLASH_Program
时,您需要指定要写入的数据的大小以及该数据的第一个字节的地址。
在我的例子中,HAL_FLASH_Program(TYPEPROGRAM_WORD, &userConfig[0], data);
一个字意味着4个字节,因此userConfig
的前4个字节被写入。这也意味着定义为uint8_t data
的参数必须与您要写入的数据大小一致,因此它应该是uint32_t data
。
我修改了代码以考虑这些注意事项。以下代码已经证明并正在运行:
//data type have to be consistent with the TYPEPROGRAM, i.e:
//TYPEPROGRAM_BYTE uint8_t data
//TYPEPROGRAM_HALFWORD uint16_t data
//TYPEPROGRAM_WORD uint32_t data
//TYPEPROGRAM_DOUBLEWORD uint64_t data
void Write_Flash(uint32_t data[],uint8_t flashTypeProgram)
{
uint8_t addressGap;
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
FLASH_Erase_Sector(FLASH_SECTOR_6, VOLTAGE_RANGE_3);
for (i=0;i<64/pow(2, flashTypeProgram);i++)
{
addressGap=pow(2, flashTypeProgram)*i;
HAL_FLASH_Program(flashTypeProgram, &userConfig[0]+addressGap, data[i]);
}
HAL_FLASH_Lock();
//TYPEPROGRAM_BYTE Program byte (8-bit) at a specified address $0
//TYPEPROGRAM_HALFWORD Program a half-word (16-bit) at a specified address $1
//TYPEPROGRAM_WORD Program a word (32-bit) at a specified address $2
//TYPEPROGRAM_DOUBLEWORD Program a double word (64-bit) at a specified address $3
}
[...]
flashTypeProgram=TYPEPROGRAM_WORD;
dataSize=(sizeof dataBuffer) / (sizeof *dataBuffer);
for (i=0;i<dataSize;i++) {
dataBuffer[i]=0x1010101; //0x1010101 puts 1 in each byte of userConfig
}
Write_Flash(dataBuffer,flashTypeProgram);