如果要节省单片机IO口,可以用一个按键,通过判断按下的时间来执行不同的子程序,自己闲来无事随意写了个,可能不够精简,但是功能都有,proteus仿真能出来,三种按键时间,短时间按下LED1亮,中等长度时间LED2亮,长时间按下LED3亮,具体按多久,自己稍微体会下就能把握
单片机长短按键仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
单片机源程序:
- #include<reg52.h>
- #include<intrins.h>
- #define uchar unsigned char
- #define uint unsigned int
- #define ulong unsigned long
- sbit keyback=P1^0;
- sbit k=P1^4;
- sbit key1=P1^1;
- sbit key2=P1^2;
- sbit key3=P1^3;
- static uint i=0;
- uchar keystay=0x00;
- uchar T0RH;
- uchar T0RL;
- void configtimer0(uchar ms)
- {
- ulong tmp;
- tmp=11059200/12;
- tmp=(ms*tmp)/1000;
- tmp=65536-tmp+10;
- T0RH=(unsigned char)(tmp>>8);
- T0RL=(unsigned char)tmp;
- TMOD &=0xF0;
- TMOD |=0x01;
- TH0=T0RH;
- TL0=T0RL;
- ET0=1;
- TR0=1;
- }
- void Judge(uint num)
- {
- if((5<num)&&(num<=50))
- {
- key1=0;
- key2=1;
- key3=1;
- i=0;
- }
- if((50<num)&&(num<=120))
- {
- key2=0;
- key1=1;
- key3=1;
- i=0;
- }
- if(num>120)
- {
- key3=0;
- key1=1;
- key2=1;
- i=0;
- }
- }
- main()
- {
- EA=1;
- configtimer0(10);
- while(1)
- {
- if((keystay&0xFF)==0x00)
- {
- Judge(i);
- }
- }
- }
-
- void keyscan()
- {
- keystay=(keystay<<1) | (!keyback);
- }
-
- void interrupt_timer0()interrupt 1
- {
- TH0=T0RH;
- TL0=T0RL;
- keyscan();
- if((keystay&0xFF)==0xFF)
- {
- i++;
-
- if(i>400)
- {
- i=0;
- }
- …………
- …………限于本文篇幅 余下代码请从51黑下载附件…………
复制代码
全部资料51hei下载地址:
长短按键.rar
(68.63 KB, 下载次数: 221)
|