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

/**********************************************************/

INT16U intv  = 0;

/**
	* @brief  Timer0初始化配置,输出测试信号
  * @param  None
  * @retval None
	*/
void init_timer0(void)
{
	/* 工作模式0：13 位定时器/计数器，计满3.64ms(13bit) */
	TL0 = (8192-2250) & 0x1F;       /* 初始值低字节，TL0 的高 3 位是无效的 */
	TH0 = (8192-2250) >> 5;         /* 初始值高字节 1ms 		*/
	TMOD = 0x00;                	 /* 定时器,时钟为系统时钟 12 分频 			*/

	INT_TIME0;		//开TIME0中断
  TIME0_OPEN;		//启动TIME0
}

/**
	* @brief  timer0中断服务
  * @param  None
  * @retval None
	*/
void timer0_isr (void) interrupt 1  
{
#if (TIMER2_CAPTURE_MODE == 0)//软件抓取	
	static INT16U last = 0;
	INT16U time_val, diff;
	/* 1ms 定时 ，模式0， 13bit*/
	TL0 = (8192-2250) & 0x1F;       
	TH0 = (8192-2250) >> 5;        
	T2CL = 0XAA;   				//软件触发捕获 定时器2
	OUT_IO = !OUT_IO;			//P03翻转
	time_val = (T2CH<<8) | T2CL;
	diff = time_val - last;
	//printf("%d %d %d %bx %bx\r\n", diff, time_val, last, T2CH, T2CL);
	last = time_val;
#else
	TL0 = (8192-113) & 0x1F;       
	TH0 = (8192-113) >> 5;        
#endif
	
	TRIG_IO = !TRIG_IO;
}

#if (TIMER2_CAPTURE_MODE == 0)
/**
	* @brief  timer2软件写抓取模式
  * @param  None
  * @retval None
	*/
void Timer2SoftCapture(void)
{
	TL2 = 0;										//Time2计数值低8位
	TH2 = 0;										//Time2计数值高8位
	
	T2MOD = T2IE + T2CM + T2CS; //T2中断使能+软件写T2CL抓取+系统时钟
	T2CON = 0x04 + 0x01;			  //T2启动信号+抓取模式
}

#elif (TIMER2_CAPTURE_MODE == 1)
/**
	* @brief  timer2硬件抓取模式
  * @param  None
  * @retval None
	*/
void Timer2HwCapture(void)
{
	TL2 = 0;										//Time2计数值低8位
	TH2 = 0;										//Time2计数值高8位
	
	T2MOD = T2IE+T2CS;					//T2中断使能+系统时钟+T2EX下降沿有效
	T2CON = 0x04+0x08+0x01;			//T2启动信号+T2EX启动信号+抓取模式
	P10_FUN_T2EX; 							//P10配置为T2EX 
}
#endif

/**
	* @brief  timer2中断服务
  * @param  None
  * @retval None
	*/
void timer2_isr (void) interrupt 5  
{
#if (TIMER2_CAPTURE_MODE == 1)
	static INT16U last = 0;
	INT16U time_val, diff;
#endif
	if(TF2 == 1)
	{
		TF2 = 0;
	}
	if(EXF2 == 1)
	{
		#if (TIMER2_CAPTURE_MODE == 1)
		time_val = (T2CH << 8) | T2CL;
		diff = time_val - last;
//		printf("%bu %bu %bu %bu %bu\r\n", diff, time_val, last, T2CH, T2CL);
		last = time_val;
		intv = diff;
		OUT_IO = !OUT_IO;
		#endif
		
		EXF2 = 0;
	}
}
/**
	* @brief  打印测试
  * @param  None
  * @retval None
	*/
void WRITE_TEST(void)
{
		printf("\ncapture:%bu\n", intv);
}

