STM32G0xx使用LL库将Flash页分块方式存储数据实现一次擦除可多次写入
参考例程
STM32G0xx HAL和LL库Flash读写擦除操作
STM32G030Cx HAL库Flash擦除或编程操作出错的解决办法
例程说明
1.Flash存储数据采用页分块方式,实现一次擦除多次写入,每块128Byte总共16块,当存满16块后擦除一次
2.将数据写入Flash前,需要前后对比数据,只有数据发生变化才能写入Flash中
3.从Flash读取数据后,进行CRC校验,校验不通过往前继续读取数据,然后重新校验数据
4.将数据写如Flash前需要确保改块都是0xFF,保证写入数据成功
一、存储到Flash中的数据
说明:
- Header用来标识存储的头部信息,在Flash读取或写入时用到
- ubRes用来作块对齐使用,默认进行128Byte对齐
#define FLASH_STORE_PARM_HEADER_TAG (0x6C5A) //固定头信息
#define FLASH_STORE_PARM_BLOCK_SIZE (128) //块大小
#define FLASH_STORE_PARM_BLOCK_COUNT (u16)(FLASH_PAGE_SIZE / FLASH_STORE_PARM_BLOCK_SIZE) //1页分块的数量
#pragma pack(1)
typedef struct
{
............
............
}GlobalParamStore, * GlobalParamStore_t;
typedef struct
{
............
............
}DemarParamStore, * DemarParamStore_t, * pDemarParamStore;
typedef struct
{
............
............
}ExceptionTrace;
typedef struct
{
............
............
}ExtraLibPara;
typedef struct
{
u16 HeaderTag;
u16 StoreIndex;
}FlashStoreHeader, * FlashStoreHeader_t;
typedef struct
{
FlashStoreHeader Header;
GlobalParamStore SysPar;
DemarParamStore DemarPar;
ExceptionTrace ExpTrace;
ExtraLibPara ExtLibPar;
u8 ubRes[16];
u8 ubCRC8;
}SystemParamStore, * SystemParamStore_t;
#pragma pack()
二、Flash最底层操作(解锁,加锁,擦除,读写)
说明:
- XSUPER_STM32G0_LL_LIB_ENABLE 被使能使用LL库
- Flash相关操作失败可多次尝试,尽可能让操作成功
#define FLASH_OPT_OVERTIMER (0x1FFFF)
#define FLASH_OPT_TRY_COUNT (5)
/* Unlock the FLASH control register access */
static u8 ubFLASH_Unlock(void)
{
u8 sta = 0;
if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00U)
{
/* Authorize the FLASH Registers access */
WRITE_REG(FLASH->KEYR, FLASH_KEY1);
WRITE_REG(FLASH->KEYR, FLASH_KEY2);
/* verify Flash is unlock */
if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00U)
{
sta = 1;
}
}
return sta;
}
/* Lock the FLASH control register access */
static u8 ubFLASH_Lock(void)
{
u8 sta = 1;
/* Set the LOCK Bit to lock the FLASH Registers access */
SET_BIT(FLASH->CR, FLASH_CR_LOCK);
/* verify Flash is locked */
if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00u)
{
sta = 0;
}
return sta;
}
/* Gets the page of a given address */
static u32 ulGetPage(u32 startAddr)
{
return ((startAddr - FLASH_BASE) / FLASH_PAGE_SIZE);
}
/* Erase the specified FLASH memory page */
static u8 ubFLASH_PageErase(u32 page)
{
u32 tmp = 0;
u32 time = 0;
u8 res = 0;
/* Get configuration register, then clear page number */
tmp = (FLASH->CR & ~FLASH_CR_PNB);
/* Set page number, Page Erase bit & Start bit */
FLASH->CR = (tmp | (FLASH_CR_STRT | (page << FLASH_CR_PNB_Pos) | FLASH_