Question
STM32H7 HAL_FLASHEx_Erase returns HAL_OK but something extrange is happening
I am trying to build an iap that reads a .bin file from a uSD card and loads it into the flash memory, but something is happening with the erase function. If i run this bootloader and the flash is empty everything works just fine. However, if the flash is not empty, the HAL_FLASHEx_Erase returns HAL_OK but then, when trying to write it crashes. If i stop the program just before the write function and go to the STM32CubeProgrammer in order to watch if the flash has been erased, if returns a "Error: Data read failed" message".
The erase function:
uint32_t FLASH_STM_M7_Erase (uint32_t StartSector)
{
uint32_t UserStartSector;
uint32_t SectorError;
FLASH_EraseInitTypeDef pEraseInit;
/* Unlock the Flash to enable the flash control register access *************/
HAL_FLASH_Unlock();
FLASH_STM_M7_Init();
/* Get the sector where start the user flash area */
UserStartSector = GetSector(APPLICATION_ADDRESS);
pEraseInit.TypeErase = FLASH_TYPEERASE_SECTORS;
pEraseInit.Sector = UserStartSector;
pEraseInit.NbSectors = 8 - UserStartSector;
pEraseInit.VoltageRange = FLASH_VOLTAGE_RANGE_3;
if (APPLICATION_ADDRESS < ADDR_FLASH_SECTOR_0_BANK2)
{
pEraseInit.Banks = FLASH_BANK_1;
if (HAL_FLASHEx_Erase(&pEraseInit, &SectorError) != HAL_OK)
{
/* Error occurred while sector erase */
return (1);
}
/* Mass erase of second bank */
pEraseInit.TypeErase = FLASH_TYPEERASE_MASSERASE;
pEraseInit.Banks = FLASH_BANK_2;
if (HAL_FLASHEx_Erase(&pEraseInit, &SectorError) != HAL_OK)
{
/* Error occurred while sector erase */
return (1);
}
}
else
{
pEraseInit.TypeErase = FLASH_TYPEERASE_SECTORS;
pEraseInit.Banks = FLASH_BANK_2;
if (HAL_FLASHEx_Erase(&pEraseInit, &SectorError) != HAL_OK)
{
/* Error occurred while sector erase */
return (1);
}
}
HAL_FLASH_Lock();
return (0);
}#define APPLICATION_ADDRESS (uint32_t)0x08020000
/////////////////////////////////////////////////////////////////////////////////////////////
if (finfno.fsize < (FLASH_SIZE - IAP_SIZE)) {
/* Erase necessary page to download image */
if (FLASH_STM_M7_Erase(APPLICATION_ADDRESS) != 0) {
state = BOOT_ERROR;
break;
}
TSC_SetTimer(bootloader_time, BOOTLOADER_TIMEOUT, s);
state = WRITE_FLASH;
break;
} else {
