5乘5的矩阵键盘,行线接P0^0到P0^4,列线接P2^0到P2^4。但是按键程序不能正确运行,问题如图,没能正确扫描。
#include<reg52.h>
void delay(int i)
{
int x,y;
for(x=i;x>0;x--)
for(y=112;y>0;y--);
}
unsigned char KeyA()
{
unsigned int a,H,L;
P0 = 0x1f; //行 0001 1111
P2 = 0x00; //列 0000 0000
if((P0 & 0x1f) != 0x1f)
{
delay(10); //按键消抖
if((P0 & 0x1f) != 0x1f)
{
H = P0;
P0 = 0x00;
P2 = 0x1f;
L = P2;
while((P2 & 0x1f) != 0x1f);
a = (10 * H) + L;
return(a);
}
}
return -1;
}
char KeyB()
{
char r;
switch( KeyA() )
{
//1
case 330: r = 0x11; break;
case 329: r = 0x12; break;
case 327: r = 0x13; break;
case 323: r = 0x14; break;
case 315: r = 0x15; break;
//2
case 320: r = 0x21; break;
case 319: r = 0x22; break;
case 317: r = 0x23; break;
case 313: r = 0x24; break;
case 305: r = 0x25; break;
//3
case 300: r = 0x11; break;
case 299: r = 0x12; break;
case 297: r = 0x13; break;
case 293: r = 0x14; break;
case 285: r = 0x15; break;
//4
case 260: r = 0x11; break;
case 259: r = 0x12; break;
case 257: r = 0x13; break;
case 253: r = 0x14; break;
case 245: r = 0x15; break;
//5
case 180: r = 0x11; break;
case 179: r = 0x12; break;
case 177: r = 0x13; break;
case 173: r = 0x14; break;
case 165: r = 0x15; break;
}
return (r);
}
void init()
{
TMOD = 0x02;
TH0 = 0xf4;
TL0 = 0xf4;
TR0 = 1;
SM0 = 0;
SM1 = 1;
}
void main()
{
init();
while(2)
{
SBUF = KeyB();
while(!
ti);
TI = 0;
}
}
一周热门 更多>