cancel
Showing results for 
Search instead for 
Did you mean: 

STM32L4 Flash erase fail with HAL_FLASH_ERROR_PGS and HAL_FLASH_ERROR_WRP

rshar.21
Associate II

Hi Everyone,

I have written a firmware which write some meta data in STM32L4 internal flash memory. But sometimes it happens that code gets stuck in a loop while erasing the flash memory. 

uint32_t UserFunctionForErasingFlash(void) {
  FLASH_EraseInitTypeDef EraseInitStruct;
  uint32_t SectorError = 0;
  uint32_t Success=1;

  EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
  EraseInitStruct.Banks       = GetBank(MDM_FLASH_ADD);
  EraseInitStruct.Page        = GetPage(MDM_FLASH_ADD);
  EraseInitStruct.NbPages     = 2;

  /* Unlock the Flash to enable the flash control register access *************/
  g_unlock_erase_flash = HAL_FLASH_Unlock();
//  clear_flash_flags();
  if(HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK){
    g_erase_error_code = HAL_FLASH_GetError();
    Success=0;
    Error_Handler();
  }

  /* Lock the Flash to disable the flash control register access (recommended
  to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  return Success;
}

Above is the code snippet, where I checked FLASH_UNLOCK is happening perfectly. And also Bank and page number are also correct. But Erasing the flash memory is giving error HAL_FLASH_ERROR_PGS and HAL_FLASH_ERROR_WRP.

 

To understand the reason, I uploaded the code again, and it gets stuck here (2 times I checked it). But when I started debugging line by line, then it worked perfectly. After erasing, write also happen correctly. 

 

Has anyone encountered a similar issue or have insight, how can I recreate this issue and why erasing the internal flash is giving this issue and how can I resolve it?

11 REPLIES 11

I do write a 64-bit at a time. when you mention partial write, I thought you are saying that I should finish writing in whole 2KB page.

In my response, flash page = 64 bits. I should have used a different term.

> I think clearing all the error flags before writing/erasing will be enough, isn't it?

If flags are getting set, you should probably diagnose why and fix that issue, rather than silently clearing them.

If you feel a post has answered your question, please click "Accept as Solution".

@TDK I'm not able to figure out, why error flags are getting set. Can you please help me out in this, what can be the reason as I'm not able to figure out?

one thing I have notice that, these errors occur only when device went to low battery and controller not able to turn ON, and when it got the battery fully charged it setting the error flags. Although these devices have gone through low battery multiple times.