/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

void delay(uint32_t ticks)
{
  while (ticks--)
    ;
}

void GPIO_LED_Init(void)
{
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);

  GPIO_Init(GPIOD, GPIO_Pin_4, GPIO_MODE_OUT | GPIO_OTYPE_PP);

  GPIO_SetBits(GPIOD, GPIO_Pin_4);
}

int main(void)
{
  SystemCoreClockUpdate();

  if (RCC_GetResetFlagStatus(RCC_RSTFLAG_WWDGRST) != RESET)
  {
    RCC_ClearResetFlags(RCC_RSTFLAG_WWDGRST);
    delay(10000000);
  }

  GPIO_LED_Init();

  RCC_APBPeriphClockCmd(RCC_APBPeriph_WWDG, ENABLE);

  WWDG_DeInit();
  WWDG_SetCounter(255);                      // 255ms
  WWDG_SetPrescaler(SystemCoreClock / 1000); // 1k
  WWDG_SetWindowValue(200);                  // 200ms
  WWDG_Cmd(ENABLE);

  /* Infinite loop */
  while (1)
  {
    delay(1000000);
    GPIO_ToggleBits(GPIOD, GPIO_Pin_4);
    /* 1. When WWDG_CNTVAL > WWDG_WINCMP, writing WWDG_RLOAD triggers MCU RESET */
    /* 2. When WWDGCNT = 0, MCU RESET is triggered */
    WWDG_SetCounter(255);
  }
}

#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif
