STM32L476 hangs when HAL_Flash_OB_Launch is called
I have multiple boards of STM32L476 board. In our application, we have OTA module in which we use dual bank feature.
The OTA flow is like:
1) Read data from SPI
2) Write to Bank 2's pages in incremental order
3) Once all data are transferred, go for flash bank switch
4) The bank switch code is as per Dual boot example provided by ST. See below snippet.
HAL_StatusTypeDef FLASH_If_BankSwitch(void)
{
FLASH_OBProgramInitTypeDef ob_config;
HAL_StatusTypeDef result;
HAL_FLASH_Lock();
/* Clear OPTVERR bit set on virgin samples */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
/* Get the current configuration */
HAL_FLASHEx_OBGetConfig( &ob_config );
ob_config.OptionType = OPTIONBYTE_USER;
ob_config.USERType = OB_USER_BFB2;
if ((ob_config.USERConfig) & (OB_BFB2_ENABLE)) /* BANK1 active for boot */
{
ob_config.USERConfig = OB_BFB2_DISABLE;
}
else
{
ob_config.USERConfig = OB_BFB2_ENABLE;
}
/* Initiating the modifications */
result = HAL_FLASH_Unlock();
/* program if unlock is successful */
if ( result == HAL_OK )
{
result = HAL_FLASH_OB_Unlock();
/* program if unlock is successful*/
if ((READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) == RESET))
{
result = HAL_FLASHEx_OBProgram(&ob_config);
}
if (result == HAL_OK)
{
HAL_FLASH_OB_Launch();
}
}
return result;
}By adding debug prints after every flash call and found that, it gets stuck at Flash_OB_Launch on some of the boards. But on other boards it is working fine. All these boards are machine assembled so all the boards are identical. So, I have somewhat more confidence on HW.
5) If we power cycle the board couple of times, then it starts with new firmware.
PS: We are using Freertos. Before calling above API, we call XTaskSuspendAll() and taskENTER_CRITICAL() to make sure no interrupt affects the switching.