FLASH_WaitForLastOperation returns error in STM32G070
I try to erase a page using this code:
bool EraseFlash()
{
uint32_t FirstPage = 0, NbOfPages = 0;
uint32_t PageError = 0;
int i;
FLASH_EraseInitTypeDef EraseInitStruct = {0};
HAL_FLASH_Unlock();
FirstPage = GetPage(FLASH_START);
/* Get the number of pages to erase from 1st page */
NbOfPages = GetPage(FLASH_END) - FirstPage + 1;
// Testing:
FirstPage = 30;
NbOfPages = 1;
/* Fill EraseInit structure*/
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Page = FirstPage;
EraseInitStruct.NbPages = NbOfPages;
printf("Erasing %d, %d\n\r", (int)FirstPage, (int)NbOfPages);
/* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache,
you have to make sure that these data are rewritten before they are accessed during code
execution. If this cannot be done safely, it is recommended to flush the caches by setting the
DCRST and ICRST bits in the FLASH_CR register. */
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
{
printf("Error %d\n\r", PageError);
return false;
}
return true;
}But it fails every time.
First time FLASH_WaitForLastOperation returns HAL_ERROR and HAL_FLASH_GetError returns 0xA0 which I interpret as errr flags FLASH_FLAG_PGSERR and FLASH_FLAG_PGAERR.
Next time I try it will always return HAL_TIMEOUT.
I have tried different pages but result is the same.
If I clear the bits above, it wil instead return HAL_TIMEOUT on first try.
Why is it behaving like this? What have I missed?
HAL_Init(), __HAL_RCC_SYSCFG_CLK_ENABLE() and __HAL_RCC_PWR_CLK_ENABLE() is enough to init flash correclty?
