/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"
#include "bsp_uart1.h"
#include <stdio.h>
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t OverflowCnt = 0;
/* Private function prototypes -----------------------------------------------*/
void PCA_Init(void);
/* Private functions ---------------------------------------------------------*/

/* UART1 will print message about every 1s */
int main(void)
{
  SystemCoreClockUpdate();

  uart1_init(24000000, 115200);
  PCA_Init();

  /* Infinite loop */
  while (1)
  {
    /* print message every second */
    if (OverflowCnt == 46)
    {
      OverflowCnt = 0;
      printf("One second passed.\r\n");
    }
  }
}

/* Time: 46 * 65535 / 3000000 = 1.00487s */
void PCA_Init(void)
{
  RCC_APBPeriphClockCmd(RCC_APBPeriph_PCA, ENABLE);

  PCA_BaseInitTypeDef PCA_InitStruct;
  PCA_InitStruct.ClkSrcSel = PCA_CLOCK_SOURCE_PCLKDIV8;
  PCA_InitStruct.RunInIdleMode = PCA_IDLEMODE_DISABLE;
  PCA_BaseInit(&PCA_InitStruct);

  PCA_ITConfig(PCA_IT_OVERFLOW, ENABLE);
  NVIC_SetPriority(PCA_IRQn, 1);
  NVIC_EnableIRQ(PCA_IRQn);

  PCA_Cmd(ENABLE);
}

void PCA_IRQHandler(void)
{
  if (PCA_GetFlagStatus(PCA_FLAG_OVERFLOW) != RESET)
  {
    PCA_ClearITPendingBit(PCA_IT_OVERFLOW);
    OverflowCnt++;
  }
}

#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
