Skip to main content
MOhamed_Mehery
Associate III
March 28, 2023
Solved

I am having an issue with my STM32F446 where I am experiencing a hardfault right after calling HAL_FLASH_Program to write data to internal flash, when I check the CFSR registerI see that the UNDEFINSTR flag is set to high.

  • March 28, 2023
  • 3 replies
  • 1255 views

I am using the following code to write data to flash memory:

#include "stm32f4xx_hal.h"

#include "stm32f4xx_hal_flash.h"

#define DATA_SIZE 4

int main(void)

{

   uint32_t data[DATA_SIZE] = {0x12345678, 0x90ABCDEF, 0xDEADBEEF, 0xCAFEBABE};

   uint32_t address = 0x08000040; // Starting address of sector 0

   HAL_Init();

   HAL_FLASH_Unlock(); // Unlock flash

   // Erase sector 0

   FLASH_Erase_Sector(FLASH_SECTOR_0, FLASH_VOLTAGE_RANGE_3);

   // Write data to flash

   for (int i = 0; i < DATA_SIZE; i++) {

       if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, data[i]) != HAL_OK) {

           // Handle write error

       }

       address += sizeof(data[i]);

   }

   HAL_FLASH_Lock(); // Lock flash

   while (1) {

       // Main loop

   }

}

Could you please help me understand why I am experiencing a hardfault and what is causing the

UNDEFINSTR

flag to be set to high in the

CFSR

register?

Thank you in advance for your help.

Best regards,

This topic has been closed for replies.
Best answer by Tesla DeLorean

Use FLASH that's not hosting your code.

You might need to make a hole in the F4 memory map to free a smaller block.

You need some bootable code at 0x08000000​

3 replies

ST Technical Moderator
March 28, 2023

Hello @MOhamed_Mehery​,

Have you tried the example provided on Cube Firmware? Here is a link STM32CubeF4/Projects/STM32F446ZE-Nucleo/Examples/FLASH/FLASH_EraseProgram at master · STMicroelectronics/STM32CubeF4 (github.com)

If still facing same issue, ensure that the data you are trying to write to flash is properly formatted and aligned.

To give better visibility on the answered topics, please click on "Best answer" on the reply which solved your issue or answered your question.Best regards,FBL
waclawek.jan
Super User
March 28, 2023

Which memory/address do you run this code from? You are erasing beginning of FLASH - do you remap area 0x0000'0000, and/or relocate VTOR appropriately?

JW

Tesla DeLorean
Tesla DeLoreanBest answer
Guru
March 28, 2023

Use FLASH that's not hosting your code.

You might need to make a hole in the F4 memory map to free a smaller block.

You need some bootable code at 0x08000000​

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..