Skip to main content
Senior II
October 27, 2023
Question

HAL_FLASHEx_Erase HardFault_Handler STM32G030K8

  • October 27, 2023
  • 18 replies
  • 5452 views

Hello,

I have developed an application that saves accelerometer data when a machine starts up. This data is stored in the last page of the controller's memory (page 31).

I'm encountering a HardFault exception that occurs intermittently, roughly 1 in 20 to 50 times when running the code with the debugger attached. However, it consistently happens when flashing and running the application without the debugger.

I'm seeking guidance on how to effectively debug this issue. Here's a snippet of the relevant code:

The page parameter is 31, with a size of 1 when this function is called.

Any assistance in troubleshooting this problem would be greatly appreciated.

 

 

static _Bool flash_erase_pages(uint8_t page,uint8_t size)
{
	static FLASH_EraseInitTypeDef EraseInitStruct;
	uint8_t bResult=0;
	uint8_t retry=0;

	static volatile uint32_t flasherror;
	uint32_t PAGEError;

	do{
		/* Unlock the Flash to enable the flash control register access *************/
		HAL_FLASH_Unlock();

		 /* Clear OPTVERR bit set on virgin samples */
		__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);


		/* Fill EraseInit structure*/
		EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
		EraseInitStruct.Banks = FLASH_BANK_1 ;
		EraseInitStruct.Page = (uint32_t)page;
		//EraseInitStruct.NbPages = ((EndPage - StartPage)) +1;
		EraseInitStruct.NbPages = size;

		if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
		{
			/*Error occurred while page erase.*/
			flasherror = HAL_FLASH_GetError ();
		}
		else{
			bResult = 1;
		}

		HAL_FLASH_Lock();

		if(bResult) 	return true;
		HAL_Delay(1);
		if(++retry>5) 	return false;
	}while(1);
}

 

 



on the occasional times i was able to generate this while i was debuggin i got these data :

The HardFault happens in HAL_FLASH_Lock(); ->  SET_BIT(FLASH->CR, FLASH_CR_LOCK);

before we enter the HardFault  i see this data in the flash_erase_pages function.
PAGEError = 2103
PAGEError = 536876972 (another time)

Which seems to make no sense as there are only 32 pages.
flasherror =  0 

 

Upon a successful flash write, the value of PAGEError is consistently 0xFFFFFFFF. I'm perplexed by what might be causing this unexpected behavior.

Here's the structure of EraseInitStruct for your reference:

image.png


Thank you 

This topic has been closed for replies.

18 replies

Pavel A.
October 31, 2023

Then how come that return address in LR points to RAM? Stack overwrite, again?

sde c.1Author
Senior II
October 31, 2023

If I had a clear answer, I would provide it. To truly understand what happens when a Hard Fault occurs, I need to delve deeper into the study of STM registers, assembly, and their inner workings. For now i got the issue fixed , thanks to checking all my code and make sure no repeats are happening just likeTDK proposed, but i do not know what triggered the Fault.