51单片机加按键控制LED花样闪烁(非用中断),51中用一个main主函数来控制led花样闪烁,实现和用中断控制差不多的效果...
单片机源程序如下:
- #include<reg51.h>
- #define uchar unsigned char
- #define uint unsigned int
- #define lei unsigned char
- lei q=0;
- sbit KEY=P3^2;
- uchar before=0;
- int temp=0;
- //延迟---还会用于消抖
- void Delay(uint x) {
- uchar i;
- while(x--){
- for(i=0;i<120;i++);
- }
- }
- //延迟1
- void delay_1() {
- unsigned char i,j;
- for(i=0;i<250;i++)
- {
- if(KEY==0)
- break;
- for(j=0;j<250;j++);
- }
- }
- //样式2 按下之前的流水灯
- void a1(){
- P2=0xff;
- if(temp>7)
- temp=0;
- if(before==1){
- temp+=2;
- before=0;
- }
- P2&=~(1<<(temp++));
- Delay(150);
- }
- //样式3
- void a2() {
- P2=0xff;
- if(temp<0)
- temp=7;
- if(before==1){
- temp-=2;
- before=0;
- }
- P2&=~(128>>(7-temp--));
- Delay(150);
- }
- //样式4 往外两端亮去
- void a3(){
- P2=0xff;
- P2=0xcc;
- delay_1();
- P2=0xff;
- P2=0x33;
- delay_1();
- }
- //按下次数
- char Key_Scan(){
- if(KEY==0){
- Delay(4);
- while(KEY==0);
- before=1;
- q++;
- if(q==3)
- q=0;
- }
- return q;
- }
- void main(){
- P2=0xff;
- while(1){
- while(1){
- Key_Scan();
- switch(q%3){
- case 0: a1();break;
- case 1: a2();break;
- case 2: a3();break;
- //case 3: a4();break;
- }
- }
- }
- }
复制代码
所有资料51hei提供下载:
甭中断之key control led 花样闪.rar
(63.41 KB, 下载次数: 13)
|