#include "timer2.h"

//#define TIMER2_MODE0	//16位自动重载模式
#define TIMER2_MODE1	//16位捕获模式
//#define TIMER2_MODE2	//可编程时钟输出
//#define TIMER2_MODE3	//递增/递减计数器


void T2_Init(void)
{
	#ifdef TIMER2_MODE0		//16位自动重载模式
	//配置定时器初值
	TH2 = 0xFC;
	TL2 = 0x18;	
	T2CPH = 0xFC;		//配置定时器重载值
	T2CPL = 0x18;	 //
	T2MOD = 0x80;  //选择系统时钟 系统不分频
	T2CON = 0x04;	 // timer2 16位自动重载模式		TR2=1
	#endif
	
	#ifdef TIMER2_MODE1		//16位捕获模式
	P2CR &= 0xDF;
	ALFSEL1 |= 0x20;		//复用P25为T2外部捕获输入
	TH2 = 0xFC;
	TL2 = 0x18;	
	T2MOD = 0x80;		//选择系统时钟
	T2CON = 0x09;		//16位带捕获检测T2EX引脚上的下降沿
	T2CPH = 0xFC;		//存储计数器的高8位
	T2CPL = 0x18;	 //
	T2CON |= 0x04;		//TR2 = 1	CP/RL2 = 1
	#endif
	
	#ifdef TIMER2_MODE2		//可编程时钟输出
	T2MOD = 0x82;		//选择系统时钟，T2作为可编程时钟输出
	P2CR |= 0x10;
	ALFSEL1 |= 0x10;	//P24配置为T2时钟输出
	TH2 = 0xFF;
	TL2 = 0x9C;	
	T2CPH = 0xFF;		//T2CP1	存放波形周期数据
	T2CPL = 0x9C;
	T2CON |= 0x04;	//TR2 = 1		C/T2=0下可以做可编程时钟
	#endif
	
	#ifdef TIMER2_MODE3		//递增/递减计数器
	//配置定时器初值
	TH2 = 0xFC;
	TL2 = 0x18;	
	T2CPH = 0xFC;		//配置定时器重载值
	T2CPL = 0x18;	 //
	T2MOD = 0x81;  //选择系统时钟 系统不分频;DCEN置1作为递增递减计数器
	P2CR &= 0xDF;
	P2PCR |= 0x20;
	ALFSEL1 |= 0x20;//P25输入为1则递减
	T2CON = 0x04;	 // timer2 16位自动重载模式		TR2=1
	#endif
}


void Timer2_Test()
{
	
	#ifdef TIMER2_MODE0			//P10输出频率为1kHz的方波
	EA = 1;
	IEN1 = 0x03;
	T2_Init();
  GPIO_OUTPUT(P1, 0, 0);		//设置IO为输出[P1.0=0]：
	#endif
	
	#ifdef TIMER2_MODE1			//P25捕获
	EA = 1;
	IEN1 = 0x03;	
	T2_Init();
	#endif
	
	#ifdef TIMER2_MODE2			//可编程时钟 P24输出5kHz
	EA = 1;
	IEN1 = 0x03;	
	T2_Init();
	#endif
	
	#ifdef TIMER2_MODE3
	EA = 1;
	IEN1 = 0x03;	
	T2_Init();
	GPIO_OUTPUT(P1, 0, 0);		//设置IO为输出[P1.0=0]：
	#endif
	while(1);
}

