硬件: STC89C50
目标:获取矩阵键盘的按键值(按下按键,在单个数码管上显示出键值)
连线: P1与矩阵键盘连接,P0 与单个数码管连接
代码如下:
#include <reg51.h>
unsigned char code table[] = {0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
//数码管共阴级
unsigned char code table1[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
//数码管共阳级
unsigned char code table2[]= {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void delay(unsigned char num)
{
while(num--);
}
int KeyNum()
{
int m;int n;
int keyVal;
P1 = 0xf0;
if(P1 != 0xf0)
{
delay(5);
if(P1 == 0xB0)
{
m = 1;
}
else if(P1 == 0xD0)
{
m = 2;
}
else if(P1 == 0xE0)
{
m = 3;
}
}
P1 = 0x0f;
if(P1 != 0x0f)
{
delay(5);
if(P1 == 0x07)
{
n = 1;
}
else if(P1 == 0x0B)
{
n = 2;
}
else if(P1 == 0x0D)
{
n = 3;
}
else if(P1 == 0x0E){
n = 4;
}
}
keyVal = (m-1)*4+n;
return keyVal;
}
int main()
{
int keyVal;
P1 = 0xf0;
while(1)
{
if(P1 != 0xf0)
{
keyVal = KeyNum();
P0 = table1[keyVal];
}
P1 = 0xf0;
}
}