例1 按键检测程序
//功能:当按下S8键时,L1灯发光,松手后,L1灯熄灭。相应程序如例1.#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit D1=P1^0;
sbit S1=P3^4;
void main()
{
P3=0xff;
while(1)
{
if(S1==0)
delay(20);//消除按下时的抖动
if(S1==0)
{
D1=0;
while(!S1);//松手检测
delay(20);//消除松手时的抖动
}
else
D1=1;
}
}
例2 按键检测程序
//功能:当每按下S8键时,数码管自动加1,当加到F时又从零开始。
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit duan=P2^6;
sbit wei=P2^7;
sbit S1=P3^4;
uchar temp;
uchar code table[]=
{0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
void delay(uint z )
{
uint x ,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void main()
{
P3=0xff;
wei=1;
P0=0xfe;
wei=0;
temp=0;
while(1)
{
if(S1==0)
{
delay(20);//消除按下时的抖动
if(S1==0)//
{
temp++;
if(temp==16)temp=0;
}
while(!S1);//松手检测,防止temp一次多加
delay(20);//消除松手时的抖动
while(!S1);
}
duan=1;
P0=table[temp];
duan=0;
}
}
|