Erasing a Flash Page of STM32L4R5 doesn’t work
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()