目录
STM32F103RC使用HAL库对FLASH的擦除与写入(代码模块)
一、芯片FLASH简介
二、FALSH的擦除
三、FALSH的写入
STM32F103RC使用HAL库对FLASH的擦除与写入(代码模块)
一、芯片FLASH简介
stm32f103rc芯片的flash大小为256KB,分为128页,每页大小为2KB。
二、FALSH的擦除
uint8_t flash_erase(void) {uint32_t PageError = 0;uint8_t *p;p = (uint8_t *)((uint32_t *)0x08004000UL)FLASH_EraseInitTypeDef FlashEraseInit = {.TypeErase = FLASH_TYPEERASE_PAGES,.Banks = FLASH_BANK_1,.PageAddress = 0x08004000,.NbPages = 120,}printf("擦除前FLASH地址0x08004000存放的数据为:%#x",*p);HAL_FLASH_Unlock();if(HAL_FLASHEx_Erase(&FlashEraseInit,&PageError) != HAL_OK){return 1;}HAL_FLASH_Lock();printf("擦除后FLASH地址0x08004000存放的数据为:%#x",*p);return 0; }
stm32f103rc芯片的擦除方式有两种:1、按页擦除(FLASH_TYPEERASE_PAGES) 2、按块擦除(FLASH_TYPEERASE_MASSERASE)当使用页擦除方式擦除某一页或者几页时,需要设置: .TypeErase = FLASH_TYPEERASE_PAGES, //擦除方式.Banks = FLASH_BANK_1, //擦除哪个块,该项只有擦除方式为按块擦除时才有效.PageAddress = 0x08004000, //擦除起始地址.NbPages = 120, //擦除页数当使用块擦除方式擦除某一块时,需要设置: .TypeErase = FLASH_TYPEERASE_MASSERASE,//擦除方式.Banks = FLASH_BANK_1, //擦除哪个块,该项只有擦除方式为按块擦除时才有效.PageAddress = 0x08004000, //擦除起始地址.NbPages = 1, //擦除页数
三、FALSH的写入
uint8_t flash_write(volatile uint32_t FlashAddress, uint32_t *Data, uint32_t DataLength) {uint32_t i = 0;HAL_StatusTypeDef ret;HAL_FLASH_Unlock();for(i=0; (i < DataLength) && (FlashAddress < APP_END_ADDR); i++){ret= HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,FlashAddress,*(uint32_t*)(Data+i));if(ret == HAL_OK){if(*(uint32_t *)FlashAddress != *(uint32_t *)(Data + i)){return 2; //数据校验错误}FlashAddress += 4;}else{return 1; //数据写入错误}}HAL_FLASH_Lock();return 0; }
函数形参:FlashAddress:待写入FLASH的地址Data:待写入数据的缓存区地址DataLength:待写入数据的长度 说明: APP_END_ADDR:为宏定义#define APP_END_ADDR ((uint32_t)0x0803FFFFUL)HAL库接口函数HAL_FLASH_Program的写入方式有三种:1、半字写入(FLASH_TYPEPROGRAM_HALFWORD) 16bit(2字节)2、整字写入(FLASH_TYPEPROGRAM_WORD) 32bit(4字节)3、双字写入(FLASH_TYPEPROGRAM_DOUBLEWORD)64bit(8字节)