第十七课 按键之三 矩阵按键之选择
硬件电路:
程序讲解:
/*--------------------------------------------------------------*/
//4*4矩阵键盘的设计
//Time: 21:04 2009-4-28
/*--------------------------------------------------------------*/
//包含头文件
#include <AT89X52.H>
/*--------------------------------------------------------------*/
//键盘接口定义
#define key_port P2
/*--------------------------------------------------------------*/
//延时5000+0us 函数定义
static void delay5ms(void)
{
unsigned char i,j;
for(i=185;i>0;i--)
for(j=12;j>0;j--);
}
/*--------------------------------------------------------------*/
//键盘扫描
unsigned char key_scan(void)
{
unsigned char x, y, z, k;
key_port = 0x0f; //行扫描 此时P2=00001111
if(key_port != 0x0f) //假若按键S1按下即P2.0和P2.4连在一起,此时P2.0
{ //(P2.0=1)的高电平会被P2.4(P2.4=0)的低电平拉低 ,故
delay5ms(); //当按键S1按下后 P2=00001110
if(key_port != 0x0f)
{
x = key_port; //保存行扫描时有键按下的状态,即将P2=00001110赋给x保存
key_port = 0xf0; //列扫描 此时P2=11110000 S1按下后变成11100000,高拉低
y = key_port; //保存列扫描时有键按下的状态 即将P2=11100000赋给y保存
z = x|y; //x|y(对应位相或)后得到11101110即0xee 赋给z,即按下S1后
//z=0xee
switch(z) // 通过判断z的值来标记K,直白点说就是当S1按下时,k标记为0
{ //当S2被按下是通过分析上面程序可知z=0xde,此时k标记为1
//以此类推.....
case 0xee: k = 0; break; //对键值赋值
case 0xde: k = 1; break;
case 0xbe: k = 2; break;
case 0x7e: k = 3; break;
case 0xed: k = 4; break;
case 0xdd: k = 5; break;
case 0xbd: k = 6; break;
case 0x7d: k = 7; break;
case 0xeb: k = 8; break;
case 0xdb: k = 9; break;
case 0xbb: k = 10; break;
case 0x7b: k = 11; break;
case 0xe7: k = 12; break;
case 0xd7: k = 13; break;
case 0xb7: k = 14; break;
case 0x77: k = 15; break;
}
while(key_port != 0xf0); //等待按键松开
}
}
return (k); //返回键值
}
/*--------------------------------------------------------------*/
//主函数
void main(void)
{
while(1)
{
P1 = ~key_scan(); //显示按键键值即标记的k值
}
}
本节重点:
1、矩阵按键行扫列扫的理解
2、switch(z) 语句的应用
相关程序:https://static.assets-stash.eet-china.com/album/old-resources/2009/6/1/e2ccb8e4-a75c-49ac-a89a-7e638be92af5.rar
用户550735 2009-6-2 23:24
用户204680 2009-6-2 18:47
用户1663879 2009-6-2 15:54