第一次再这个论坛分享,如有错误,还请批评指正。配合单片机开发板使用的程序,当按下按键1时,LED每隔1S闪烁一次;当按下按键2时,流水灯从左往右流水,当按下按键3时,流水灯从左往右流水流水,当按下按键4时,LEDD灯全灭;
单片机源程序如下:
- #include<reg51.h>
- #include"stdio.h"
- sbit K1 = P3^0;
- sbit K2 = P3^1;
- sbit K3 = P3^2;
- sbit K4 = P3^3;
- unsigned char code table[]={0xc0,0xf9,0xa4,0xb0,0x99};
- unsigned char code table1[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
- unsigned char code table2[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
- void delay1() //@12.000MHz
- {
- unsigned char i, j;
- i = 12;
- j = 169;
- do
- {
- while (--j);
- } while (--i);
- }
- void delay(unsigned int n)
- {
- unsigned char i;
- for(i=0;i<n;i++)
- {
- delay1();
- }
- }
- void Cls_Peripheral(void) //关闭外设;
- {
- P0 = 0XFF;
- P2 = P2 & 0X1F | 0X80;
- P2 &= 0X1F;
- P0 = 0;
- P2 = P2 & 0X1F | 0XA0;
- P2 &= 0X1F;
- }
- void Set_74HC138(unsigned char outnum) //打开某一位的开关;
- {
- P2 &= ~(0x7<<5);
- P2 |= ((outnum&0x07)<<5);
- }
- void led_init(unsigned char n) //选择某个数字;
- {
- Set_74HC138(6); //打开位选段
- P0 = 0X01;
- P2 = 0X1F;
- Set_74HC138(7); //打开段选端;
- P0 = table[n];
- P2 = 0X1F;
- }
- void main(void)
- { char KEY1=0, KEY2=0,KEY3=0,KEY4=0,j=0;
- static char z=0,l=0;
- Cls_Peripheral(); //关外设?
- while(1)
- {
- if(K1 == 0)
- {
- KEY1 = 1;
- KEY2 = 0;
- KEY3 = 0;
- KEY4 = 0;
- }
- if(K1 == 1 && KEY1 == 1)
- {
- led_init(1);
- P2 =0X1F;
- Set_74HC138(4);
- {
- P0 = 0xFF;
- delay(100);
- P0 = 0X00;
- delay(100);
- }
- }
- if(K2 == 0)
- {
- KEY2 = 1;
- KEY1 = 0;
- KEY3 = 0;
- KEY4 = 0;
- }
- if(K2 == 1 && KEY2 == 1)
- {
- led_init(2);
- P2 =0X1F;
- Set_74HC138(4);
- {
- P0 = table1[z];
- z++;
- delay(110);
- if(z==8) z=0;
- }
- }
- if(K3 == 0)
- {
- KEY3 = 1;
- KEY1 = 0;
- KEY2 = 0;
- KEY4 = 0;
- }
-
- if(K3 == 1 && KEY3 == 1)
- {
- led_init(3);
- P2 =0X1F;
- Set_74HC138(4);
- {
- P0 = table2[l];l++;
- delay(110);
- if(l==7) l =0;
- }
- }
-
- if(K4 == 0)
- {
- KEY4 = 1;
- KEY1 = 0;
- KEY3 = 0;
- KEY2 = 0;
- }
- if(K4 == 1 && KEY4 == 1)
- {
- P0 = 0XFF;
- P2 = P2 & 0X1F | 0X80;
- P2 &= 0X1F;
-
- P0 = 0X01;
- P2 = P2 & 0X1F | 0XC0;
- P2 &= 0X1F;
- P0 = 0X99;
- P2 = P2 & 0X1F | 0XE0;
- P2 &= 0X1F;
-
-
- }
- }
- }
复制代码 全部程序51hei下载地址:
按键控制.rar
(26.4 KB, 下载次数: 13)
|