/* 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);
}

void IWDG_IRQHandler(void)
{
  if (IWDG_GetITStatus(IWDG_IT_GOVF) != RESET)
  {
    /**
     * @note Two interrupts in a row that do not
     *       clear the GOVF flag cause the MCU to reset.
     */
    IWDG_ClearITPendingBit(IWDG_IT_GOVF);
    IWDG_ReloadCounter();
    GPIO_ToggleBits(GPIOD, GPIO_Pin_4);
  }
}

int main(void)
{
  SystemCoreClockUpdate();

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

  GPIO_LED_Init();

  // Enable LSI clock
  RCC_LSIConfig(LSI_VALUE_32K, RCC_LSI_STARTUP_4CYCLE, ENABLE);

  // Enable IWDG clock
  RCC_APBPeriphClockCmd(RCC_APBPeriph_IWDG, ENABLE);

  // Config IWDG
  IWDG_Init(IWDG_MODE_INT | IWDG_IT_ENABLE, ENABLE);
  NVIC_SetPriority(IWDG_IRQn, 1);
  NVIC_EnableIRQ(IWDG_IRQn);
  IWDG_SetReload(32768); // 1S
  IWDG_Start();

  /* Infinite loop */
  while (1)
  {
    ;
  }
}

#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
