1 //利用定时器 1和定时器0控制led1和led2分别 2hz和0.5hz闪烁 2 3 #include<reg52.h> 4 #define uchar unsigned char 5 #define uint unsigned int 6 sbit led1=P1^3; 7 sbit led2=P1^7; 8 uchar count0,count1; 9 10 void delay(uint x) 11 { 12 uchar i; 13 while(x--) 14 { 15 for(i=0;i<120;i++); 16 } 17 } 18 19 void init() 20 { 21 TMOD = 0x10; //定时器1 0 22 EA=1; 23 ET0=1; 24 TR0=1; 25 TH0=0x4b; 26 TL0=0xfd; //50ms 27 ET1=1; 28 TR1=1; 29 TH1=0x4b; 30 TL1=0xfd; 31 } 32 33 void main() 34 { 35 init(); 36 while(1) 37 { 38 led1=led2=1; 39 40 } 41 42 } 43 void Timer0() interrupt 1 //定时器0 44 { 45 TH0=0x4b; 46 TL0=0xfd; 47 count0++; 48 if(count0==10)//如果是500ms(2hz) 49 { 50 count0=0; 51 led1=0; 52 delay(3); 53 } 54 55 } 56 57 void Timer1() interrupt 3 //定时器1 58 { 59 TH1=0x4b; 60 TL1=0xfd; 61 count1++; 62 if(count1==40)//如果是2000ms 63 { 64 count1=0; 65 led2=0; 66 delay(3); 67 } 68 69 }
1 //利用定时器 1和定时器0控制led1和led2分别 2hz和0.5hz闪烁 2 //利用定时器0 1s,led1取反,利用计数器1,(65535-10)%256,取反 3 #include<reg52.h> 4 #define uchar unsigned char 5 #define uint unsigned int 6 sbit led1=P1^3; 7 sbit led2=P1^7; 8 uchar count0,count1; 9 10 void delay(uint x) 11 { 12 uchar i; 13 while(x--) 14 { 15 for(i=0;i<120;i++); 16 } 17 } 18 19 void init() 20 { 21 TMOD = 0x10; //定时器1 0 22 EA=1; 23 ET0=1; 24 TR0=1; 25 TH0=0x4b; 26 TL0=0xfd; //50ms 27 ET1=1; 28 TR1=1; 29 TH1=0x4b; 30 TL1=0xfd; 31 } 32 33 void main() 34 { 35 init(); 36 while(1) 37 { 38 led1=led2=1; 39 40 } 41 42 } 43 void Timer0() interrupt 1 //定时器0 44 { 45 TH0=0x4b; 46 TL0=0xfd; 47 count0++; 48 if(count0==10)//如果是500ms(2hz) 49 { 50 count0=0; 51 led1=0; 52 delay(3); 53 } 54 55 } 56 57 void Timer1() interrupt 3 //定时器1 58 { 59 TH1=0x4b; 60 TL1=0xfd; 61 count1++; 62 if(count1==40)//如果是2000ms 63 { 64 count1=0; 65 led2=0; 66 delay(3); 67 } 68 69 }