#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
#define MASK 0xf0
uchar code table[] = {0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71,
0xff}; // 段码表
uchar code table2[] = {0xfe,0xfd,0xfb,0xf7}; // 扫描
void delay(uint i);
void display(uchar num);
void keyscan(uchar * num);
int main(void)
{
uchar num = 16;
while(1)
{
keyscan(&num);
display(num);
}
return 0;
}
void keyscan(uchar * num)
{
uchar temp;
uint i;
// 扫描按键并比较
for(i = 0; i < 4; i++)
{
P2 = table2[i];
temp = P2;
temp &= MASK;
if(temp != MASK)
{
delay(5);
temp = P2;
temp &= MASK;
if(temp == MASK)
{
continue;
i--;
}
}
switch(temp)
{
case 0xe0 :
(*num) = 4 * i + 0;
break;
case 0xd0 :
(*num) = 4 * i + 1;
break;
case 0xb0 :
(*num) = 4 * i + 2;
break;
case 0x70 :
(*num) = 4 * i + 3;
break;
// default:
// break;
}
}
while((P2 & MASK) != MASK);
delay(5);
while((P2 & MASK) != MASK);
}
void delay(uint i)
{
uint j;
for(;i > 0; i--)
for(j = 0; j < 100; j++)
continue;
}
void display(uchar num)
{
P0 = ~table[num];
}
数码管是共阳极接法,数码管是单独接的 不用锁存器
键盘是4X4的键盘P2.0~P2.3控制行,2.4~2.7是列
上面这个程序,1~3排按了都有反应,第四排按下之后不一定有反应 (有时候有,排除键盘接触不良)
|