//定时器驱动

#include "BspTime3.h"
#include "bsp.h"

static void (*IRQHandler)(void) = NULL;

void TIM_Delay_Init(void)//延时定时器
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); 
	
	TIM_DeInit(TIM3);//初始化位复位值
	TIM_InternalClockConfig(TIM3);//配置内部时钟
	TIM_TimeBaseStructure.TIM_Period = 0xffff;//自动重装值;向上计数到0xffff后,计数值归零,计数到5000为5ms
	TIM_TimeBaseStructure.TIM_Prescaler =71;//预分频值,1Mhz的计数频率
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;//时钟分割为0
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//TIM向上计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);//初始化TIMx的时间基数单位
	TIM_Cmd(TIM3, DISABLE);
}

//关闭定时器
void BspTim3Close(void)
{
    TIM_Cmd(TIM3, DISABLE);
    TIM_SetCounter(TIM3, 0);
    TIM_ITConfig(TIM3, TIM_IT_Update, DISABLE);
}

void TIM_DelayUs(u16 i)//1~65535us延时	  
{
	u16 TIMCounter = 0;
	TIM_SetCounter(TIM3, TIMCounter);
	TIM_Cmd(TIM3, ENABLE);
	while (TIMCounter<i)
	{
		TIMCounter = TIM_GetCounter(TIM3);
	}
	TIM_Cmd(TIM3, DISABLE);
}


//通用定时器4初始化，
void BspTim4Init(void)
{
    NVIC_InitTypeDef NvicInitdef;
    TIM_TimeBaseInitTypeDef timbase;	
    u16 cnt = 170 * 72;     //170us 触发

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);	

    TIM_DeInit(TIM4); 
    timbase.TIM_CounterMode = TIM_CounterMode_Up;
    timbase.TIM_ClockDivision = TIM_CKD_DIV1;
    timbase.TIM_Period = cnt - 1;
    timbase.TIM_Prescaler = 0; 	        // 1分频
    TIM_TimeBaseInit(TIM4, &timbase);

    NvicInitdef.NVIC_IRQChannel = TIM4_IRQn;
    NvicInitdef.NVIC_IRQChannelPreemptionPriority = 0;
    NvicInitdef.NVIC_IRQChannelSubPriority = 2;
    NvicInitdef.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NvicInitdef);

    TIM_SetCounter(TIM4, 0);
    TIM_ITConfig(TIM4, TIM_IT_Update, DISABLE);
    TIM_ClearITPendingBit( TIM4, TIM_IT_Update);

    /* TIMX enable counter */
    TIM_Cmd(TIM4, DISABLE);
}

//使能能定时器
void BspTim4Open(void)
{
    TIM_SetCounter(TIM4, 0);
    TIM_Cmd(TIM4, ENABLE);
    TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
}

//关闭定时器
void BspTim4Close(void)
{
    TIM_Cmd(TIM4, DISABLE);
    TIM_SetCounter(TIM4, 0);
    TIM_ITConfig(TIM4, TIM_IT_Update, DISABLE);
}

//设置计数值
void BspTim4SetCounter(u16 count)
{
    TIM_SetCounter(TIM4, count);
}

//定义中断函数
void BspTim4SetIRQCallBack(void *fun)
{
    IRQHandler = (void (*)(void))fun;
}

//timx中断函数
void TIM4_IRQHandler(void)
{
    if( SET == TIM_GetITStatus(TIM4,TIM_IT_Update) )
    {
        TIM_ClearITPendingBit( TIM4, TIM_IT_Update);

        if (IRQHandler != NULL)
            (*IRQHandler)();//中断函数
    }
}
