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

uint8_t Linear_motion_flag = 0;
uint16_t TIM1_cnt = 0;
uint16_t TIM1_rot_cnt = 0;
uint16_t Rot_current_time = 0;
uint16_t TIM1_pit_cnt = 0;
uint16_t Pit_current_time = 0;

//SP_MSP_DH_Handset_Parameters DH_WH_HandSet;

//返回值：：1-正常；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)  //TIM1,TIM8高级定时器
{
	//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);

		if(DH_WH_BING->Mov_Horiz1_vert2 == 1)
		{
			if(++TIM1_cnt >= 200) //20s
			{
				TIM1_cnt = 0;
				Linear_motion_flag = !Linear_motion_flag;
			}
		}

		if(DH_WH_BING->Mode_A1_B2 == 1)
		{
			if((++TIM1_rot_cnt % 10) == 0)  //1s
			{
				Rot_current_time = Rot_current_time + 1;
			}
		}
		if(DH_WH_BING->Mode_C1_D2 == 1)
		{
			if((++TIM1_pit_cnt % 10) == 0)
			{
				Pit_current_time = Pit_current_time + 1;
			}
		}

	}
	//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;
            }
        }
    }
}
