Skip to main content
Associate II
January 23, 2026
Question

Writing to flash generates a HardFault

  • January 23, 2026
  • 4 replies
  • 251 views

Hi,

I'm busy with my own BootLoader. I can erase the flash, required to store the program. But writing to the flash causes a HardFault. (I also write to flash in my application to store the configuration. That seems to work, so (normally) I can write to the flash without any problems).

My routine looks as follows (msg.Data is the received information from my PC. The contents look fine):

 HAL_FLASH_Unlock();
 uint64_t* pData = (uint64_t*)&msg.Data;
 while (m_CurrentAddress < tempEndAddress)
 {
 HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, m_CurrentAddress, *pData);
 m_CurrentAddress += 8;
 pData++;
 }
 HAL_FLASH_Lock();

 The debugger shows this information:

ErX_0-1769163253275.pngErX_1-1769163274310.png

I do not know how to (further) debug this information.

Thanks in advance.

Greetings,

ErX

4 replies

ErXAuthor
Associate II
January 23, 2026

If I change the messing around with the pData pointer, and just use data like this:

 HAL_FLASH_Unlock();
 uint8_t nIndex{};
 uint64_t Data{};
 while (m_CurrentAddress < tempEndAddress)
 {
 memcpy(&Data, &msg.Data[nIndex], sizeof(Data));
 HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, m_CurrentAddress, Data);
 m_CurrentAddress += 8;
 nIndex += 8;
 }
 HAL_FLASH_Lock();

It works just fine. (even though I do not really understand the big difference).

Ozone
Principal
January 23, 2026

> I do not know how to (further) debug this information.

The first recommendation is to switch to "instruction stepping", i.e. debugging on machine code level.
Doing so right before the "C" code line the hardfault hits is sufficient.
Watching the registers and associated values, this should give you a clue.

Second / alternative recommendation is to check the fault registers in the SCB block of the MCU.
They indicate the source of the fault.

Technical Moderator
January 23, 2026

Hello @ErX 

Please refer to the article below to debug the HardFault:

How to debug a HardFault on an Arm® Cortex®-M STM3... - STMicroelectronics Community

"To give better visibility on the answered topics, please click on ""Accept as Solution"" on the reply which solved your issue or answered your question.Saket_Om"
TDK
Super User
January 23, 2026

Probably you are writing to the same memory address twice without erasing, which is not allowed.

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