求助关于矩阵键盘点亮LED灯
我将矩阵键盘引脚与P2口相连。该历程中,利用2组P3口返回值定位按下的键,继而点亮LED灯。我编写的程序如下:
#include<reg51.h>
sbit LED1 = P3^0;
sbit LED2 = P3^1;
sbit LED3 = P3^2;
sbit LED4 = P3^3;
sbit LED5 = P3^4;
sbit LED6 = P3^5;
sbit LED7 = P3^6;
sbit LED8 = P3^7;
void Delay(unsigned int i);
void Key(void);
void main()
{
while(1)
{
Key();
}
}
void Key(void)
{
unsigned char i = 0;
unsigned char j = 0;
unsigned char k = 0;
unsigned char KEY_Value = 0;
P2 = 0x0F;
i = P2;
if(i != P2)
{
Delay(1000);// 延时消抖
P2 = 0x0F;// 输入0xFF
i = P2;// 返回P2值
if(i != P2)// 监测是否有按键按下
{
P2 = 0x0F;
i = P2;// 返回值1
P2 = 0x70;
j = P2;// 返回值2
P2 = 0x7F;
k = i|j;// 两返回值按位或得到定位键盘的值
switch(k)// 定位按下的键盘
{
case 0x37:
{
KEY_Value = 1;
break;
}
case 0x3B:
{
KEY_Value = 2;
break;
}
case 0x3D:
{
KEY_Value = 3;
break;
}
case 0x3E:
{
KEY_Value = 4;
break;
}
case 0x57:
{
KEY_Value = 5;
break;
}
case 0x5B:
{
KEY_Value = 6;
break;
}
case 0x5D:
{
KEY_Value = 7;
break;
}
case 0x5E:
{
KEY_Value = 8;
break;
}
case 0x67:
{
KEY_Value = 9;
break;
}
case 0x6B:
{
KEY_Value = 10;
break;
}
case 0x6D:
{
KEY_Value = 11;
break;
}
case 0x6E:
{
KEY_Value = 12;
break;
}
}
P2 = 0x0F;// 判断键盘是否松开
i = P2;
P2 = 0x70;
j = P2;
P2 = 0x7F;
k = i|j;
while(k != 0x7F)
{
P2 = 0x0F;
i = P2;
P2 = 0x70;
j = P2;
P2 = 0x7F;
k = i|j;
}
}
}
switch(KEY_Value)// 利用不同的键盘点亮/熄灭不同的LED灯
{
case 1: LED1 = ~LED1;break;
case 2: LED2 = ~LED2;break;
case 3: LED3 = ~LED3;break;
case 4: LED4 = ~LED4;break;
case 5: LED5 = ~LED5;break;
case 6: LED6 = ~LED6;break;
case 7: LED7 = ~LED7;break;
case 8: LED8 = ~LED8;break;
case 9: LED1 = ~LED1;break;
case 10: LED2 = ~LED2;break;
case 11: LED3 = ~LED3;break;
case 12: LED4 = ~LED4;break;
}
}
void Delay(unsigned int i)
{
while(-- i);
}
i = P2; // 返回值1无效 因为被按下 p2=00001101
P2 = 0x70; 无效 因为被按下 p2=00001101
j = P2; // 返回值2无效 因为被按下 p2=00001101
P2 = 0x7F;无效 因为被按下 p2=00001101
k = i
[解决办法]
j; // 无效 因为被按下 p2=00001101