STM32 Flash Erase Fails: HAL_FLASHEx_Erase() Doesn't Reset Bytes to 0xFF
Hello ST Community,
I'm currently facing a challenging issue with my STM32L476RET6 where I'm unable to erase a specific page in the flash memory. Despite the HAL_FLASHEx_Erase() function returning HAL_OK, indicating the erase operation was supposedly successful, the bytes at the specified memory location are not set to 0xFF as expected. I've confirmed this by checking the memory location with STM32CubeProgrammer.
Environment:
MCU: STM32L476RET6
IDE: STM32CubeIDE
OS: Windows 10
Here's the function where I'm encountering the issue:
HAL_StatusTypeDef set_update_flag(void) {
// Unlock the Flash to enable the flash control register access
HAL_StatusTypeDef status = HAL_FLASH_Unlock();
if (status != HAL_OK) {
// Unlock failed, handle accordingly
return status;
}
// Define the page and bank for the erase operation
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PageError = 0;
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Banks = FLASH_BANK_1;
EraseInitStruct.Page = 255; // Targeting the last page for the erase operation
EraseInitStruct.NbPages = 1;
// Erase the page
status = HAL_FLASHEx_Erase(&EraseInitStruct, &PageError);
if (status != HAL_OK) {
// Erase failed, handle accordingly
HAL_FLASH_Lock(); // Make sure to lock the flash again before returning
return status;
}
// Set the update flag to 1
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, UPDATE_FLAG_ADDRESS, 0x0000000100000001);
if (status != HAL_OK) {
// Program failed, handle accordingly
HAL_FLASH_Lock(); // Make sure to lock the flash again before returning
return status;
}
HAL_FLASH_Lock(); // Lock the Flash to disable the flash control register access
return HAL_OK;
}
Interestingly, there's no HAL_ERROR after calling HAL_FLASHEx_Erase(), but PageError returns 0xFFFFFFFF. This leads to a HAL_ERROR when attempting to write to the memory location afterwards with HAL_FLASH_Program().
I've previously had this functionality working, but it's currently not behaving as expected, and I'm at a bit of a loss. I've checked and re-checked the page number and confirmed that the flash is being unlocked successfully. The same goes for the flash lock at the end of the operation.
Has anyone encountered a similar issue or have insights into what might be going wrong? Any suggestions or advice would be greatly appreciated.
Thank you in advance for your help!
Adrian.
