没有下拉电阻,如果没有下拉电阻,没有被按键时,引脚是高组态,这个时候不能用来读取数据,必须将用来读的引脚加上下拉电阻拉到地,这样才能读数据,所以你需要4个下拉电阻在键盘上。。。。 记住引脚悬空,又没有上拉或下拉电阻的时候不要读数据,这时候读的东西是不会出现你想要的结果,可能1,可能0 ,有上拉无输入时,是1,下拉式0,你这里面希望是无输入时引脚为0,所以用下拉。。。。
#include
unsigned char led[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void led_display(unsigned char num);
unsigned char key_scan();
unsigned char temp,key;
sbit led1=P2^0;
sbit led2=P2^1;
void main()
{
unsigned char led_key;
P1=0;
while(1)
{
led_key=key_scan();
led_display(key);
}
}
void led_display(unsigned char num)
{
unsigned char ten,single;
int delay;
ten=num/10;
single=num%10;
delay=100;
for(delay=200;delay>0;delay--)
{
P0=led[ten];
led1=0;
led1=1;
P0=led[single];
led2=0;
led2=1;
}
}
/////////////////////////////////////////
unsigned char key_scan(void)
{
P1=0xfe;
temp=P1&0xf0;
if(temp!=0xf0)
{
switch(temp)
{
case 0xe0: key=1;
break;
case 0xd0: key=2;
break;
case 0xb0: key=3;
break;
case 0x70: key=4;
}
return key;
}
P1=0xfd;
temp=P1&0xf0;
if(temp!=0xf0)
{
switch(temp)
{
case 0xe0: key=5;
break;
case 0xd0: key=6;
break;
case 0xb0: key=7;
break;
case 0x70: key=8;
}
return key;
}
P1=0xfb;
temp=P1&0xf0;
if(temp!=0xf0)
{
switch(temp)
{
case 0xe0: key=9;
break;
case 0xd0: key=10;
break;
case 0xb0: key=11;
break;
case 0x70: key=12;
}
return key;
}
P1=0xf7;
temp=P1&0xf0;
if(temp!=0xf0)
{
switch(temp)
{
case 0xe0: key=13;
break;
case 0xd0: key=14;
break;
case 0xb0: key=15;
break;
case 0x70: key=16;
}
return key;
}
}