//定时器驱动

#include "BspTime2.h"
#include "bsp.h"

volatile int g_Tim2Array[(u16)eTimMax] = {0};
volatile u32 sys_time=0;
volatile u16 Timerx=0;

//通用定时器初始化，
void BspTim2Init(void)
{
    NVIC_InitTypeDef NvicInitdef;
    TIM_TimeBaseInitTypeDef timbase;	

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);	

    TIM_DeInit(TIM2); 
    timbase.TIM_CounterMode = TIM_CounterMode_Up;
    timbase.TIM_ClockDivision = TIM_CKD_DIV1;
    timbase.TIM_Period = 10000 - 1;//1000=1ms;10000=10ms
    timbase.TIM_Prescaler = 72 - 1;// 72分频
    TIM_TimeBaseInit(TIM2, &timbase);

    NvicInitdef.NVIC_IRQChannel = TIM2_IRQn;
    NvicInitdef.NVIC_IRQChannelPreemptionPriority = 3;//最低优先级
    NvicInitdef.NVIC_IRQChannelSubPriority = 3;
    NvicInitdef.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NvicInitdef);

    TIM_SetCounter(TIM2, 0);
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM2, ENABLE);
}

void BspTim2Close(void)
{
    TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE);
    TIM_Cmd(TIM2, DISABLE);
}

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

//tim2中断函数
void TIM2_IRQHandler(void)
{
    u16 i = 0;

    if(SET == TIM_GetITStatus(TIM2,TIM_IT_Update))
    {
        TIM_ClearITPendingBit( TIM2, TIM_IT_Update);
//		if(!NRF_GetThreadLockState())
//		{
//			NRF_SendData();//发送数据
//			NRF_HandleBuf();//根据缓冲区状态处理缓冲区
//		}
		Led_10mS_Conut();//定期器10mS调度任务
		sys_time++;
		if(Timerx)
		{
			Timerx--;
		}
        for(i = 0; i < (u16)eTimMax; i++)
        {
            g_Tim2Array[i]++;
        }
    }
}

//注意事项:不要在中断中调用本函数,否则会存在重入问题.如果屏蔽了全局中断,则不要使用此函数
void TIM_Delay10Ms(u16 dly_10ms)
{
	Timerx=dly_10ms;
	while(Timerx)
	{
	}
}

//获取CPU运行时间,单位10ms.最长可以表示497天,如果连续运行时间超过这个数,则必须考虑溢出问题
u32 Get_RunTime(void)
{
	return sys_time;
}
