|
定時(shí)器T0被四次調(diào)用,控制led燈
0.png (62.33 KB, 下載次數(shù): 87)
下載附件
2017-4-14 20:42 上傳
- #include<reg52.h> //頭文件
- #define MY_TIMER_MAX (4) //最多四個(gè)定時(shí)器
- #define NULL (0)
- typedef void (*pFun)(void); //callback 函數(shù)指針類型
- typedef struct myTimer
- {
- char on; //開(kāi)關(guān)
- char is_period; //是否周期循環(huán)
- unsigned short int time_out; //定時(shí)時(shí)間,單位ms
- unsigned short int count; //定時(shí)計(jì)數(shù)用
- }
- MY_TIMER;
- pFun callback[MY_TIMER_MAX] = {NULL}; //定時(shí)器回調(diào)函數(shù)數(shù)組
- MY_TIMER myTimerList[MY_TIMER_MAX] = {0}; //定時(shí)器結(jié)構(gòu)數(shù)組
- int gMyTimerMessage[MY_TIMER_MAX] = {0}; //定時(shí)器消息數(shù)組
- 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;} //燈全開(kāi)
- //創(chuàng)建定時(shí)器,簡(jiǎn)化版本。
- 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;
- }
- //四個(gè)LED控制函數(shù),on初始是0,第一次調(diào)用on變?yōu)?,是關(guān)燈。
- 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) //初始化定時(shí)器0
- {
- TMOD=0x01; //定時(shí)器0,使用模式1,16位定時(shí)器
- TH0=(65536-1000)/256; //給定初值
- TL0=(65536-1000)%256;
- EA=1; //打開(kāi)總中斷
- ET0=1; //打開(kāi)定時(shí)器中斷
- TR0=1; //開(kāi)定時(shí)器
- }
- void main() //主函數(shù)
- {
- 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();//初始化定時(shí)器0
- while(1)
- {
- for(i = 0; i<MY_TIMER_MAX; ++i)
- {
- if(gMyTimerMessage[i]) //定時(shí)器消息來(lái)到,啟動(dòng)。
- {
- gMyTimerMessage[i] = 0; //消息清除
- if(callback[i] != NULL)
- {
- (*callback[i])(); //調(diào)用回調(diào)函數(shù)
- }
- }
- }
- }
- }
- //定時(shí)器中斷函數(shù),1ms 定時(shí)。
- void Timer0_isr(void) interrupt 1
- {
- unsigned int i = 0;
- TH0=(65536-1000)/256;//重新賦值 1ms
- TL0=(65536-1000)%256;
- EA = 0;
- for(i = 0; i<MY_TIMER_MAX; ++i)
- {
- if(myTimerList[i].on)
- {
- ++(myTimerList[i].count); //計(jì)數(shù)
- if(myTimerList[i].count >= myTimerList[i].time_out) //定時(shí)到
- {
- gMyTimerMessage[i] = 1; //發(fā)消息
- if(myTimerList[i].is_period) //是否周期循環(huán)
- {
- myTimerList[i].count = 0; //計(jì)數(shù)重置
- }
-
- …………限于本文篇幅 余下代碼請(qǐng)從51黑下載附件…………
復(fù)制代碼
下載:
四個(gè)led燈.zip
(20.83 KB, 下載次數(shù): 14)
2017-4-14 11:19 上傳
點(diǎn)擊文件名下載附件
定時(shí)器 下載積分: 黑幣 -5
|
|