/*
*********************************************************************************************************
*                                       IAR Development Kits
*                                              on the
*
*                                    M451
*
* Filename      : wdt_reset.c
* Version       : V1.00
* Programmer(s) : Qian Xianghong
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*                                             INCLUDE FILES
*********************************************************************************************************
*/

#include  "includes.h"

IWDG_HandleTypeDef hiwdg;

void Watchdog_Init()
{
  // 看门狗时钟为32K，超时时间为4095/(32K/256)=32秒
  hiwdg.Instance = IWDG;
  hiwdg.Init.Prescaler = IWDG_PRESCALER_256;
  hiwdg.Init.Window = 4095;
  hiwdg.Init.Reload = 4095;
  if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
  {
    Error_Handler();
  }
}

void Watchdog_Open()
{
	FLASH_OBProgramInitTypeDef OptionsBytesStruct;
	
	// 检查并设置OptionBytes的IWDG_STOP标志为：Stop模式下IWDG不工作
    HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
	printf("\r\nIWDG_STOP config: %08X\r\n", OptionsBytesStruct.USERConfig & 0x00020000);
	
	if(OptionsBytesStruct.USERConfig & 0x00020000)
	{
		HAL_FLASH_Unlock();
		__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); 
		HAL_FLASH_OB_Unlock();

		OptionsBytesStruct.OptionType = OPTIONBYTE_USER;
		OptionsBytesStruct.USERType = OB_USER_IWDG_STOP;
		OptionsBytesStruct.USERConfig &= (~0x00020000);
		
		HAL_FLASHEx_OBProgram(&OptionsBytesStruct);
		HAL_FLASH_OB_Launch();
	}
}

void Watchdog_Feed()
{
	HAL_IWDG_Refresh(&hiwdg);
}

