STM32H7 - Write float value into flash memory permanently
Hello Everyone,
I'm trying to write a float value into my STM32H743VIT6 flash memory, bit it jumps straight to the HardFaultHandler and I cannot understand why...

Here's the two functions:
HAL_StatusTypeDef Store_AltitudeMax(float altitude)
{
HAL_StatusTypeDef status;
uint32_t FirstSector, NbOfSectors, SectorError;
FLASH_EraseInitTypeDef EraseInitStruct;
// Ensure data is written in a full 32-byte Flash word
uint64_t FlashWord[4] = { 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF };
memcpy(&FlashWord[0], &altitude, sizeof(float));
// Unlock Flash
status = HAL_FLASH_Unlock();
if (status != HAL_OK)
{
return status;
}
// Get the sector of ALTITUDE_MAX_ADDRESS
FirstSector = GetSector(ALTITUDE_MAX_ADDRESS);
NbOfSectors = 1; // Only erase 1 sector
// Configure Erase Structure
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = VOLTAGE_RANGE;
EraseInitStruct.Banks = FLASH_BANK;
EraseInitStruct.Sector = FirstSector;
EraseInitStruct.NbSectors = NbOfSectors;
// Erase Flash Sector
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK)
{
HAL_FLASH_Lock();
return HAL_ERROR;
}
// Program the Flash word (32 bytes)
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, ALTITUDE_MAX_ADDRESS, (uint32_t)FlashWord);
// Lock Flash after programming
HAL_FLASH_Lock();
return status;
}
float Retrieve_AltitudeMax(void)
{
float altitude = 0.0f;
uint64_t FlashWord[4];
// Read from Flash (direct memory access)
memcpy(FlashWord, (uint64_t*)ALTITUDE_MAX_ADDRESS, sizeof(FlashWord));
// Extract stored float value
memcpy(&altitude, &FlashWord[0], sizeof(float));
return altitude;
}
And the test snippet :
HAL_StatusTypeDef ret = Store_AltitudeMax(768);
if(ret != HAL_OK) {
printf("Something went wrong with the storage of the variable! \r\n");
} else {
HAL_Delay(3000);
float value = Retrieve_AltitudeMax();
printf("Altitude retrieved: %d \r\n", (int)value);
}
Can anyone tell me what's going on here ?
