I am trying to write to flash memory from the firmware itself.
It looks like the Erase process hangs for 2 seconds or so but works, but the writing process seems to totally freeze the MCU cause a HARD FAULT. Below is the code I am using. Any idea why?
FLASH_EraseInitTypeDef flashErase;
flashErase.TypeErase = TYPEERASE_SECTORS;
flashErase.VoltageRange = FLASH_VOLTAGE_RANGE_3;
flashErase.Sector = FLASH_SECTOR_7;
flashErase.NbSectors = 1;
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);
uint32_t sectorError;
if (HAL_FLASHEx_Erase(&flashErase, §orError) != HAL_OK) {
error = true;
}
if (HAL_FLASH_Program(TYPEPROGRAM_WORD, 0x08060000, 123) != HAL_OK) {
error = true;
}
HAL_FLASH_Lock();
EDIT: The microcontroller actually triggers a HARD FAULT
I tried locating some user data to 0x08020000 (sector 5) using linker script and initializing it as follows:
__attribute__((__section__(".user_data"))) char userConfig[4] = {1, 2, 3, 4};
I can check that it is properly located and initialized (&userConfig[0] is 0x08020000 and the values are 1 2 3 4), and properly erased (back to 255 255 255 255 if I just do an erase of sector 5), but trying to write to 0x08020000 always makes an HARD FAULT happen.
EDIT2: I tried to execute the code in the RAM (using direct registers access instead of calling HAL methods) and it doesn't make any difference