51单片机的独立键盘
扫描二维码
随时随地手机看文章
这几天打算好好开始看郭天祥的单片机视频,自己也写了一个独立键盘的51单片机程序,开发环境为Keil C51。
刚开始看,功能并不是很复杂,由51单片机的P1^7口接LED灯,P0口作为6位数码管的位选线和段选线,6位数码管每次显示相同的数字。位选和段选的控制由P2^7,P2^6口。按键只有一个,一端与地相连,一端接P3^7口。
当按下按键时,LED灯会发光,同时6位数码管显示的数字加1,从0~F后返回0。松开按键后,LED灯灭。
闲话少说,上代码:
#include
#defineucharunsignedchar
sbitRDKey=P3^7;
sbitLED=P1^7;
sbitdula=P2^6;
sbitwela=P2^7;
ucharcodetable[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
voidShortDelay();
voidLongDelay();
voiddisplay(ucharnum);
voidmain()
{
ucharnum=0;
RDKey=1;
LED=1;
while(1)
{
if(RDKey==0)//键可能被被按下,需要消抖,用到了LongDelay函数
{
LongDelay();
if(RDKey==0)//键被按下,DoSomething,这里是数码管显示数字
{
LED=0;
//Dosomething
display(num);
num++;
if(num>=16)
num=0;
}
}
else
{
LED=1;
//DoOtherThing
}
}
}
voiddisplay(ucharnum)
{
wela=1;
P0=0xc0;
wela=0;
P0=0xff;
dula=1;
P0=table[num];
dula=0;
ShortDelay();//数码管动态显示,用到的是ShortDelay函数
}
voidShortDelay()
{
uchara=100;
while(a--);
}
voidLongDelay()
{
inta=10000;
while(a--);
}