/********************************************************************************
 * @file    TIM_TimeBase.c
 * @author  SOC AE Team
 * @version V1.1
 * @date    2025-06-27
 * @brief   TIM作为定时器，定时频率为1000Hz@APB0Clock=32M。
 *
 *******************************************************************************/
#include "sc32_conf.h"
#include "Function_Init.h"
#include "stdio.h"

static uint16_t TIM_BaseCnt = 0;

void TIM_TimeBase_Function(void)
{
  TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

  /* 使能TIM0时钟 */
  RCC_APB0Cmd(ENABLE);
  RCC_APB0PeriphClockCmd(RCC_APB0Periph_TIM0, ENABLE);

  /* TIM配置结构体初始化 */
  TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);

  /* 设置TIM配置结构体 */
  TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;	//TIM工作在向上计数模式
  TIM_TimeBaseInitStruct.TIM_EXENX = TIM_EXENX_Disable;	//外部重加载管脚失能
#if defined(SC32f10xx)||defined(SC32f12xx)
  TIM_TimeBaseInitStruct.TIM_Preload = 65535 - (32000000 / 1000);	//设置TIM的定时器评论为1000Hz@APB0Clock=32M
#endif
  TIM_TimeBaseInitStruct.TIM_Prescaler = TIM_PRESCALER_1;	//TIM分频为1分频
  TIM_TimeBaseInitStruct.TIM_WorkMode = TIM_WorkMode_Timer;	//TIM工作在定时器模式，时钟源为APB0时钟

  /* TIM时基配置 */
  TIM_TIMBaseInit(TIM0, &TIM_TimeBaseInitStruct);

  /* 使能TIM0中断 */
  TIM_ITConfig(TIM0, TIM_IT_TI | TIM_IT_INTEN, ENABLE);
  NVIC_EnableIRQ(TIMER0_IRQn);

  /* TIM外设初始化 */
  TIM_Cmd(TIM0, ENABLE);

  while(1)
  {
    if(TIM_BaseCnt >= 500)
    {
      TIM_BaseCnt = 0;
      printf("TIM interrupt has been triggered 500 times.\r\n");
    }
  }
}

void TIM_TimeBase_TIM0Handler(void)
{

  /* 判断TIM0中断是否置起 */
  if(TIM_GetFlagStatus(TIM0, TIM_Flag_TI) == SET)
  {
    TIM_ClearFlag(TIM0, TIM_Flag_TI);	//清除TIM0中断
    TIM_BaseCnt ++;
  }
}
