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

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define LPTIMx_FREQ        1 /* 1Hz */
#define LPTIMx_RELOADVALUE (0xFFFF - 32768 / LPTIMx_FREQ)
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
void LPTIM_Init(void);
void LED1_Init(void);
/* Private functions ---------------------------------------------------------*/

void delay(volatile uint32_t n)
{
  while (n--)
    ;
}

/* You can see LED toggle and uart1 print message every 1s */
int main(void)
{
  SystemCoreClockUpdate();
  RCC_LSIConfig(LSI_VALUE_32K, RCC_LSI_STARTUP_4CYCLE, ENABLE); // Start LSI clock

  LED1_Init();
  LPTIM_Init();
  uart1_init(24000000, 115200);

  /* Infinite loop */
  while (1)
  {
    delay(500000);
    __WFI();                            // Enter into sleep mode continuously
    GPIO_ToggleBits(GPIOD, GPIO_Pin_4); // Every 1 seconds LED toggle
    printf("1s passed\r\n");            // Every 1 second uart1 print message
  }
}

void LED1_Init(void)
{
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
  GPIO_Init(GPIOD, GPIO_Pin_4, GPIO_MODE_OUT | GPIO_SPEED_HIGH | GPIO_PUPD_UP | GPIO_OTYPE_PP);
  GPIO_ResetBits(GPIOD, GPIO_Pin_4);
}

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

  RCC_APBPeriphClockCmd(RCC_APBPeriph_LPTIM, ENABLE);

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

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

  LPTIM_TCKCmd(ENABLE);
  LPTIM_Cmd(ENABLE);
  /* To avoid unnecessary waiting */
  LPTIM_SetCounter(LPTIMx_RELOADVALUE);
}

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

#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
