2022-09-06 04:54 PM
I'm trying to erase a Flash Page of from my firmware Application with STM32L4R5 using the function 'HAL_FLASHEx_Erase()'. The Application Presence Key is stored in this page. It needs to be erased by the Application to activate the Bootloader (this is not the internal Bootloader) in Firmware Update mode.
The test code is copied below. It works properly if it is in the main() function of the Bootloader. However, erasing the page fails if the code is in the main function of the Application. The function returns ‘HAL_ERROR’ and the flashStatus is not 0xFFFFFFFF as it should be.
Does anybody know if I’m missing something here?
FLASH_EraseInitTypeDef EraseInitStruct; // Flash Page Erase Structure
uint32_t flshStatus = 0; // Flash Page Erase Status
// Flash Erase Structure Init
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Banks = FLASH_BANK_2; // Bank 2
EraseInitStruct.Page = 255; // Last Flash Page
EraseInitStruct.NbPages = 1; // One Page
// Unlock FLASH Control Register
HAL_FLASH_Unlock();
// Clear OPTVERR Bit Set on Virgin Samples
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
// Erase Specified Flash Page
uint32_t retStat = HAL_FLASHEx_Erase(&EraseInitStruct, &flshStatus);
// Lock FLASH Control Register
HAL_FLASH_Lock()
Solved! Go to Solution.
2022-12-02 06:39 AM
Hi,
Unlocking the flash wasn't the issue. The solution was clearing two more flags:
// Unlock FLASH Control Register
HAL_FLASH_Unlock();
// Clear Bits Set on Virgin Samples
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGSERR);
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR);
// Erase Specified Flash Page
HAL_FLASHEx_Erase(&EraseInitStruct, &flashStatus);
// Lock FLASH Control Register
HAL_FLASH_Lock();
Thanks!
2022-12-02 01:04 AM
Hello @Shadow
Try Unlock the flash before the init of structure to erase.
I understand that the function of erased is not yet called but Unlocking Flash mechanism may need the whole structure to be set before. It is like it could be overriden after that.
After try to write some words and read it back. So that you won't leave it empty after locking.
To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.
2022-12-02 06:39 AM
Hi,
Unlocking the flash wasn't the issue. The solution was clearing two more flags:
// Unlock FLASH Control Register
HAL_FLASH_Unlock();
// Clear Bits Set on Virgin Samples
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGSERR);
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR);
// Erase Specified Flash Page
HAL_FLASHEx_Erase(&EraseInitStruct, &flashStatus);
// Lock FLASH Control Register
HAL_FLASH_Lock();
Thanks!