1.LED呼吸灯
#include <REGX51.H>
sbit LED=P2^0;
void delay(unsigned int t)
{while(t--);
}
void main()
{unsigned char time,i;while(1){for(time=0;time<100;time++){for(i=0;i<20;i++){LED=0;delay(time);LED=1;delay(100-time);}}for(time=100;time>0;time--){for(i=0;i<20;i++){LED=0;delay(time);LED=1;delay(100-time);}}}
}
2.直流电机调速
按键数码管分别显示 1234,同时LED灯也会以呼吸灯形式闪烁越来越亮
#include <REGX51.H>
sbit LED=P2^7;
unsigned char keynumber=0;
unsigned char s[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D};
unsigned char count=0,num=0;
unsigned char counter,compare,speed;
void inittimer()
{TMOD &= 0xF0;TMOD |= 0x01;TL0 = 0x9C; //设置定时初值 100us,如果计数器计数器100,周期为10msTH0 = 0xFF; //设置定时初值TF0=0;ET0=1;//开启定时器0的中断EA=1;//开启总中断TR0=1;//启动定时器0}
void delay(unsigned int n)//1ms
{unsigned char a,b,c,m;for(m=n;m>0;m--)for(c=1;c>0;c--)for(b=142;b>0;b--)for(a=2;a>0;a--);
}
unsigned char key()
{if(P1_0==0){delay(20);while(P1_0==0);delay(20);keynumber=1;}if(P1_1==0){delay(10);while(P1_1==0);delay(10);keynumber=2;}if(P1_2==0){delay(10);while(P1_2==0);delay(10);keynumber=3;}if(P1_3==0){delay(20);while(P1_3==0);delay(20);keynumber=4;}return keynumber;
}void main()
{inittimer();while(1){keynumber=key();if(keynumber==1){speed++;speed%=4;if(speed==0){compare=0;}if(speed==1){compare=10;}if(speed==2){compare=50;}if(speed==3){compare=100;}}P2=s[keynumber];}
}
void timer_isr() interrupt 1 //0表示外部中断0;1表示定时器中断0;2表示外部中断1;3表示定时器中断1;4表示串口中断
{TL0 = 0x9C; //设置定时初值TH0 = 0xFF; //设置定时初值counter++;counter%=100;//ifcounter>=100,counter=0;if(counter<compare){LED=0;}else{LED=1;}
}