#include "TIM5_Delay.h"

void TIM5_US_CALC(uint32_t us)
{
    u16 counter=us&0xffff;
    TIM_Cmd(TIM5,ENABLE);
    TIM_SetCounter(TIM5,counter); //设置计数值

    while(counter>1)
    {
        counter=TIM_GetCounter(TIM5);
    }
    TIM_Cmd(TIM5,DISABLE);
}

void TIM5_MS_CALC(uint32_t ms)
{
    u16 counter=(ms*100)&0xFFFF; //前提定时器时钟为100KHz
    TIM_Cmd(TIM5,ENABLE);
    TIM_SetCounter(TIM5,counter); //设置计数值
    
    while(counter>1)
    {
        counter=TIM_GetCounter(TIM5);
    }
    TIM_Cmd(TIM5,DISABLE);
}

void TIM5_S_CALC(uint32_t s)
{
    u16 counter=(s*1250)&0xFFFF; //前提定时器时钟为1250Hz
    TIM_Cmd(TIM5,ENABLE);
    TIM_SetCounter(TIM5,counter); //设置计数值
    
    while(counter>1)
    {
        counter=TIM_GetCounter(TIM5);
    }
    TIM_Cmd(TIM5,DISABLE);
}

void TIM5_Init_Query(CALC_TYPE type,uint32_t val)
{
	TIM_TimeBaseInitTypeDef Tim5;
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE);
	Tim5.TIM_Period=1; //???
	if(type==CALC_TYPE_US)
	{	
		Tim5.TIM_Prescaler=72-1; //1MHz ,计数1次为us
	}
	else if(type==CALC_TYPE_MS)
	{
		Tim5.TIM_Prescaler=720-1; //100KHz ,定时器计数100次为1ms
	}
	else if(type==CALC_TYPE_S) //延时以S为单位时，时钟频率57600Hz，外部需要1250次计时
	{
		Tim5.TIM_Prescaler=57600-1; //预分频 72MHz / 57600= 1250Hz
	}	
	else
	{
		Tim5.TIM_Prescaler=7200-1;
	}
	Tim5.TIM_ClockDivision=0;
	Tim5.TIM_CounterMode=TIM_CounterMode_Down; //向下计数
	TIM_TimeBaseInit(TIM5,&Tim5);	

#if 0
	if(type==CALC_TYPE_US)
	{	
		TIM5_US_CALC(val);
	}
	else if(type==CALC_TYPE_MS)
	{
		TIM5_MS_CALC(val);
	}
	else if(type==CALC_TYPE_S)
	{
		TIM5_S_CALC(val);
	}	
	else
	{
		;
	}
#endif	
}




int TIM5_TEST_main()
{
    SystemInit(); //库函数 初始化系统时钟源选择,PLL等  

#ifdef _DEBUG
    Init_PD11();
#endif
    TIM5_Init_Query(CALC_TYPE_US, 0);

    while(1)
    {
        //PD11_U; //产生方波
        TIM5_US_CALC(1);   //TIM5_MS_CALC(1); 毫秒延时, TIM5_S_CALC(1); 秒级别延时 
        //PD11_D;
        TIM5_US_CALC(1);
    }
}

