1. 程式人生 > >51微控制器自定義多個軟體定時器

51微控制器自定義多個軟體定時器

/*----------------------------------------------------
	名稱:用定時器控制led亮滅
	微控制器:stc12c2052
	晶振:12M
	說明:四個led,四種頻率亮。
------------------------------------------------------*/
#include		//標頭檔案

#define MY_TIMER_MAX	(4)		//最多四個定時器
#define NULL (0)

typedef void (*pFun)(void);		//callback 函式指標型別
typedef struct myTimer{
	char on;						//開關
	char is_period;					//是否週期迴圈
	unsigned short int time_out;	//定時時間,單位ms
	unsigned short int count;		//定時計數用
	}MY_TIMER;

pFun callback[MY_TIMER_MAX] = {NULL};			//定時器回撥函式陣列
MY_TIMER myTimerList[MY_TIMER_MAX] = {0};		//定時器結構陣列
int gMyTimerMessage[MY_TIMER_MAX] = {0};		//定時器訊息陣列

sbit LED1=P1^0;
sbit LED2=P1^1;
sbit LED3=P1^2;
sbit LED4=P1^3;

#define ALL_ON {LED1=0;LED2=0;LED3=0;LED4=0;}	//燈全開

//建立定時器,簡化版本。
int CreatTimer(int index,unsigned short int time_out,char is_period,pFun callbackFun)
{
	if(index >= MY_TIMER_MAX) return -1;
	myTimerList[index].on = 1;
	myTimerList[index].is_period = is_period;
	myTimerList[index].time_out = time_out;
	myTimerList[index].count = 0;
	callback[index] = callbackFun;
	return index;
}

//四個LED控制函式,on初始是0,第一次呼叫on變為1,是關燈。
void led_1_ctrl(void)
{
	static char on = 0;
	on = !on;
	LED1 = on;
}
void led_2_ctrl(void)
{
	static char on = 0;
	on = !on;
	LED2 = on;
}
void led_3_ctrl(void)
{
	static char on = 0;
	on = !on;
	LED3 = on;
}
void led_4_ctrl(void)
{
	static char on = 0;
	on = !on;
	LED4 = on;
}

void Init_Timer0(void)	//初始化定時器0
{
	TMOD=0x01;				//定時器0,使用模式1,16位定時器
	TH0=(65536-1000)/256;	//給定初值
	TL0=(65536-1000)%256;
	EA=1;		//開啟總中斷
	ET0=1;	//開啟定時器中斷
	TR0=1;	//開定時器
}

void main()	//主函式
{
	unsigned int i;

	ALL_ON;
	CreatTimer(0,250,1,led_1_ctrl);
	CreatTimer(1,500,1,led_2_ctrl);
	CreatTimer(2,1000,1,led_3_ctrl);
	CreatTimer(3,2000,1,led_4_ctrl);

	Init_Timer0();//初始化定時器0
	while(1)
	{
		for(i = 0; i= myTimerList[i].time_out)		//定時到
			{
				gMyTimerMessage[i] = 1;								//發訊息
				if(myTimerList[i].is_period)						//是否週期迴圈
				{
					myTimerList[i].count = 0;						//計數重置
				}
				else
				{
					myTimerList[i].on = 0;							//關掉定時器
				}
			}
		}
	}
	EA = 1;
}