Flash read / write issue on H5 (H573) => Runs onto NMI when reading the FLASH
Hello,
I'm working on a software port from a STM32F413 to a STM32H573. I'm done with the application but I'm facing issues with the bootloader.
On H5 it looks like it's possible to write flash only with 128 bits sections. On F4 it was possible with 8 bits and 32 bits.
In order to handle the legacy code, I've writen this function that reads the 128 bits, replaces a part by my 8 new bits and then writes it back.
Here the code:
static bool _BOARD_writeFlash(WORD_SIZE wordSize, uint32_t* writeData, uint32_t writeAdr)
{
bool ret = true;
if (HAL_OK == HAL_FLASH_Unlock())
{
if (WORD_SIZE_8 == wordSize) // uint8
{
uint32_t quadWord[4]; // Array to hold 16 bytes (128 bits)
uint32_t alignedAddress = writeAdr & ~0xF; // Align address to 16-byte boundary
while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) {
// Wait for the flash controller to be ready
}
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);
// Read the current quadword from flash (16 bytes)
for (int i = 0; i < 4; i++) {
quadWord[i] = *((volatile uint32_t*)(alignedAddress + (i * sizeof(uint32_t))));
}
uint32_t offset = writeAdr % 16; // Offset within the 16-byte quadword
uint32_t wordIndex = offset / 4; // Identify the 32-bit word containing the byte
uint32_t byteShift = (offset % 4) * 8; // Calculate shift for the byte in the word
quadWord[wordIndex] &= ~(0xFF << byteShift); // Clear the target byte
quadWord[wordIndex] |= ((*writeData & 0xFF) << byteShift); // Set the new byte value
ret = ret && (HAL_OK == HAL_FLASH_Program(FLASH_TYPEPROGRAM_QUADWORD, alignedAddress, (uint32_t)quadWord));
}
HAL_FLASH_Lock();
}
else
{
FLASH_FUNC_LOGE("Can't unlock flash");
ret = false;
}
return ret;
}
Sorry for the bad quality code, I'm just trying to make this work. I'll clean right after.
This function also handles 16 bits word size write in the same way and it works perfectly fine (No NMI).
I run onto a NMI right after the first call to "quadWord[i] = *((volatile uint32_t*)(alignedAddress + (i * sizeof(uint32_t))));"
The problematic instruction is "add r2, sp, #24":

Does anyone already faces this issue while porting code from F4 to H5? Any clue or workaround?
I'll appreciate!
