cancel
Showing results for 
Search instead for 
Did you mean: 

Erasing flash sector works, but writing it causes HARD FAULT

g239955_stm1
Associate II

I am trying to write data in the flash of an STM32F446RE, sector 5.

My linker script is configured so that .user_data goes to 0x08020000, and:

__attribute__((__section__(".user_data"))) char userConfig[4] = {1, 2, 3, 4};

Is my user Data.

If I read it after flashing, I properly debug 1 2 3 4 values.

If I try to erase sector 5, it works and the values now display 255 255 255 255.

However, if I try to program anything, an HARD FAULT occurs (see code below).

Do you have any idea ?

FLASH_EraseInitTypeDef flashErase;
  flashErase.TypeErase = TYPEERASE_SECTORS;
  flashErase.VoltageRange = FLASH_VOLTAGE_RANGE_1;
  flashErase.Sector = FLASH_SECTOR_5;
  flashErase.NbSectors = 1;
  uint32_t sectorError;
 
  HAL_FLASH_Unlock();
 
  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                        FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR |
                        FLASH_FLAG_PGSERR);
 
  if (HAL_FLASHEx_Erase(&flashErase, &sectorError) != HAL_OK) {
    error = true;
  } else {
    // If this is not used, the values correctly goes to 255, else an HARD FAULT occurs...
    if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, (uint32_t)&userConfig[0], 123) != HAL_OK) {
      error = true;
    }
  }
 
  HAL_FLASH_Lock();

5 REPLIES 5

Pretty sure 123 isn't a valid address in this context​

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
g239955_stm1
Associate II

123 is not an address but a value, arguments of HAL_FLASH_Program are the type (BYTE, HALFWORD, WORD, DOUBLEWORD), the address and the data to be written

g239955_stm1
Associate II

Ultimately the code end up in FLASH_Program_Byte where the following is done:

*(__IO uint8_t*)Address = Data;

Address being 0x08020000 because it is the result of (uint32_t)&userConfig[0]

(I checked)

TDK
Guru

Duplicate:

https://community.st.com/s/question/0D53W00000NUvRBSA1/stm32f446re-freezes-when-trying-to-write-to-flash-sector-7

What does the MCU say about the source of the hard fault?

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

Thanks @TDK​, I investigated the memory using STLINK debug and figured out that it was a MMARVALID + DACCVIOL fault, then I checked how the MPU is managed.

I am using MBED as environment and I missed this page that basically explains two of my problems.

The MPU is pre-configured by the framework to disable both writing in ROM and executing of RAM. You need to declare explicitly if you want it to be possible using `ScopedRomWriteLock` or `ScopedRamExecutionLock`

https://os.mbed.com/docs/mbed-os/v6.4/apis/mpu-management.html