/*
 * bsp_TIMER.c
 *
 *  Created on: Oct 26, 2023
 *      Author: shiya
 */
#include "bsp_TIMER.h"

//返回值：：1-正常；0-错误

int16_t ctn_100ms = 0;
int16_t ctn_100ms_2 = 0;
int16_t ctn_100ms_3 = 0;
int16_t ctn_100ms_4 = 0;


uint16_t TIM1_rot_cnt = 0;
double Rot_current_time = 0;
uint16_t TIM1_pit_cnt = 0;
double Pit_current_time = 0;
uint64_t cnt_2ms = 0;


uint8_t GF_BSP_TIMER_Init()
{
    HAL_TIM_Base_Start_IT(&htim1);
	HAL_TIM_Base_Start_IT(&htim8);
    return 1;
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	//100ms - WatchDog
	if(htim->Instance == TIM1)//APB2=200Mhz,htim1.Init.Prescaler = 2000-1;htim1.Init.Period = 10000-1;  TIM1=100ms
	{
		GF_BSP_Interrupt_Run_CallBack(DF_BSP_InterCall_TIM1_100ms_PeriodElapsedCallback);
	}
	//2ms - MainLoop
	if(htim->Instance == TIM8)//APB2=200Mhz,htim8.Init.Prescaler = 2000-1;htim8.Init.Period = 200-1;  TIM8=2ms
	{
		GF_BSP_Interrupt_Run_CallBack(DF_BSP_InterCall_TIM8_2ms_PeriodElapsedCallback);
	}
}

void GF_BSP_TIMER_DelayUS(uint32_t n)
{
    uint32_t ticks;
    uint32_t told;
    uint32_t tnow;
    uint32_t tcnt = 0;
    uint32_t reload;

	reload = SysTick->LOAD;
    ticks = n * (SystemCoreClock / 1000000);

    tcnt = 0;
    told = SysTick->VAL;

    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
            	break;
            }
        }
    }
}
