废话不多说直接上代码,我把读写dataflash封装成了两个API函数:写数据函数FMC_WriteDataFlash(uint32_t *u32Config, uint32_t u32Count),
读数据函数FMC_ReadDataFlash(uint32_t *u32Config, uint32_t u32Count),注意是以u32为最小单位,也就是4个字节。
最重要的一点:写数据之前需要先把整页数据擦除,不然会写入不成功,每次只能读到0xFFFFFFFF!!! 这让我纠结了一整天,还好顺利解决了。
以下是函数定义,很简洁明了,附件是DataFlash.c和DataFlash.h文件,方便坛友直接下载。
#define FMC_USERF_BASE 0x0001F000 //用户数据FLASH起始地址
/**
* @brief Read the User Configuration words.
* @param[out] u32Config The word buffer to store the User Configuration data.
* @param[in] u32Count The word count to be read.
* @retval 0: Success
* @retval -1: Failed
*/
int32_t FMC_ReadDataFlash(uint32_t *u32Config, uint32_t u32Count)
{
int32_t i;
uint32_t data_buff[128]={0};
for(i = 0; i < u32Count; i++)
u32Config = FMC_Read(FMC_USERF_BASE + i * 4);
return 0;
}
/**
* @brief Write User Configuration
*
* @param u32Config: The word buffer to store the User Configuration data.
* @param u32Count: The word count to program to User Configuration.
*
* @retval 0: Success
* @retval -1: Failed
*
* @Details User must enable User Configuration update before writing it.
* User must erase User Configuration before writing it.
* User Configuration is also be page erase. User needs to backup necessary data
* before erase User Configuration.
*/
int32_t FMC_WriteDataFlash(uint32_t *u32Config, uint32_t u32Count)
{
int32_t i;
FMC_Erase(FMC_USERF_BASE);//写入数据前先擦除整页数据,否则从第2次开始后写入数据不成功!
for(i = 0; i < u32Count; i++)
{
FMC_Write(FMC_USERF_BASE + i * 4, u32Config);
if(FMC_Read(FMC_USERF_BASE + i * 4) != u32Config)
return -1;
}