/*Copyright (C), 2024-2030
*文件名:	USER.c
*版  本:	Ver1.00
*日  期:	2025/04/30
*描  述:	常用函数定义
*备  注:     
**********************************************************/
#include "Timer.h"
#include "BL51F003T.h"	

Timer_Delay_Params TIMER2;

/* 毫秒延时 */
void Timer2_delay_ms(INT16U ms)
{
	if (ms > 0)
	{
		T2MOD = 0;    
		T2CON = 0;
		TIMER2.Timer_Num = 0;
		TIMER2.Delay_Num = ms;
		
		T2CL = (65535 - 2250 + OFFSET); 	// 27M/12*2250 = 1ms
		T2CH = (65535 - 2250 + OFFSET) >> 8;  
		TL2 = T2CL;
		TH2 = T2CH;
		T2MOD = 0x80;  	//T2中断使能+系统时钟12分频   
		INT_TIMER2;			//TIME2中断配置
		T2CON = 0x04;	  //T2启动信号
		
		while (TIMER2.Flag == 0);
		TIMER2.Flag = 0;
		
		T2CL = 0;
		T2CH = 0;
	}
}

/* 微秒延时,MAX_us=2427 */
void Timer2_delay_us(INT16U us)
{	
	if (us > 1)
	{
		if (us < 6)
		{
			while (--us);
		}
		else
		{
			TL2 = 27*(us-5); 	// 1/27M*27 = 1us
			TH2 = 27*(us-5) >> 8; 
			T2MOD = 0x21;    
			T2CON = 0x04;
			
			while (!TF2);
			T2CON = 0;
		}
	}
}

/* Timer2 中断服务函数 */
void timer2_isr (void) interrupt 5  
{	
	TF2 = 0;
	TIMER2.Timer_Num++;
	if (TIMER2.Timer_Num == TIMER2.Delay_Num)
	{
		TIMER2.Flag = 1;
		TR2 = 0;		//T2关闭
	}
}