/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"
#include "bsp_uart1.h"
#include <stdio.h>

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define SECOND_TIMES           1000 /* 1000 / 1khz = 1s */
#define LPTIMx_FREQ            1000 /* 1KHz */
#define LPTIMx_RELOADVALUE     (0xFFFF - 24000000 / LPTIMx_FREQ)
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t LpTimUpdateCnt = 0;
/* Private function prototypes -----------------------------------------------*/
void LPTIM_Init(void);
/* Private functions ---------------------------------------------------------*/

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

  uart1_init(24000000, 115200);
  LPTIM_Init();

  /* Infinite loop */
  while (1)
  {
    /* Every 0.001s LPTIM will count overflow and generate a interrupt，
       1 second passed when there are 1000 interrupts */
    if (LpTimUpdateCnt == SECOND_TIMES)
    {
      LpTimUpdateCnt = 0;
      printf("One second passed\r\n");
    }
  }
}

void LPTIM_Init(void)
{
  LPTIM_BaseInitTypeDef Base_InitStruct = {0};

  RCC_APBPeriphClockCmd(RCC_APBPeriph_LPTIM, ENABLE);
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);

  Base_InitStruct.ClkSel = LPTIM_CLOCK_SOURCE_PCLK;
  Base_InitStruct.CntTimSel = LPTIM_TIMER_SELECT;
  Base_InitStruct.AutoReload = LPTIM_AUTORELOAD_ENABLE;
  Base_InitStruct.Period = LPTIMx_RELOADVALUE;
  Base_InitStruct.TogEnable = LPTIM_TOG_ENABLE;
  LPTIM_BaseInit(&Base_InitStruct);

  LPTIM_ITCmd(ENABLE);
  NVIC_SetPriority(LPTIM_IRQn, 1);
  NVIC_EnableIRQ(LPTIM_IRQn);

  LPTIM_TCKCmd(ENABLE);
  LPTIM_Cmd(ENABLE);
}

void LPTIM_IRQHandler(void)
{
  if (LPTIM_GetITStatus() != RESET)
  {
    LPTIM_ClearITPendingBit();
    LpTimUpdateCnt++;
  }
}

#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
