|
端口寄存器的值只能軟件改變,按鍵只是暫時(shí)改變端口電平狀態(tài),不能改變端口寄存器的值,一旦按鍵抬起,端口電平狀態(tài)恢復(fù)為端口寄存器的值。給你一個(gè)4*4矩陣鍵盤(pán)程序參考,每句都有注釋?zhuān)浑y理解。
#include <reg52.h> //頭文件
#define uchar unsigned char //宏定義
#define uint unsigned int //宏定義
uchar key=0; //鍵值變量
void key_scan() //矩陣鍵盤(pán)掃描函數(shù)
{
uchar temp1,temp2,temp3; //臨時(shí)變量
static bit sign=0; //按鍵自鎖標(biāo)志
static uchar count=0; //消抖計(jì)數(shù)變量
P3=0xf0; //先給P3賦一個(gè)初值1111 0000
if(P3!=0xf0) //判斷P3不等于所賦初值,說(shuō)明有健按下
{
if(sign==0) //如果按鍵自鎖標(biāo)志為0
{
count++; //消抖計(jì)數(shù),摒棄Delay延時(shí)方式
if(count>=250) //估算主循環(huán)周期調(diào)整100~255
{
sign=1; //按鍵自鎖標(biāo)志置1,鍵不抬起,按其他鍵無(wú)效
temp1=P3; //temp1保存高4位變化xxxx 0000
P3=0x0f; //再給P3賦值0x0f 0000 1111
temp2=P3; //temp2保存低4位變化0000 xxxx
temp3=temp2|temp1; //temp3=temp2按位與temp1,等效于低4位+高4位
key=temp3; //保存鍵值
}
}
}
else //按鍵抬起
{
sign=0; //按鍵自鎖標(biāo)志清0
count=0; //消抖計(jì)數(shù)清0
}
}
void main()
{
while(1)
{
key_scan(); //鍵盤(pán)掃描
P1=key; //LED低電平亮顯示鍵值
}
} |
|