51单片机矩阵键盘检测程序

本文介绍了一个基于51单片机的键盘扫描程序实现细节,包括按键值的读取、防抖处理及返回键值等功能。通过逐行扫描的方式确保了对键盘上16个按键的有效识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<reg52.h>  

#define uchar unsigned char
#define uint  unsigned int

uchar code table[]={
0xc0,0xf9,0xa4,0xb0, 
0x99,0x92,0x82,0xf8, 
0x80,0x90,0x88,0x83, 
0xc6,0xa1,0x86,0x8e};

void delayms(uint a)
{
uint x,y;
for(x=a;x>0;x--)
for(y=110;y>0;y--);
}

uchar keyscan()
{
uchar  temp;
static uchar keyvalue=0;   //定义静态按键值,否则每次进来会清零,也可以定义全局变量
P1=0xfe;   //清零P1口第0位,检测
temp=P1&0xf0;
if(temp!=0xf0)
{
delayms(5);  
temp=P1&0xf0;
if(temp!=0xf0)
{
if(temp==0xe0)
keyvalue=1;       //test
if(temp==0xd0)
keyvalue=2;
if(temp==0xb0)
keyvalue=3;
if(temp==0x70)
keyvalue=4;
}
while(temp!=0xf0)//等待松手,很重要
temp=P1&0xf0;//一直检测输入状态
}
P1=0xfd; //清零P1口第1位,检测
temp=P1&0xf0;
if(temp!=0xf0)
{
delayms(5);  
temp=P1&0xf0;
if(temp!=0xf0)
{
if(temp==0xe0)
keyvalue=5;       //test
if(temp==0xd0)
keyvalue=6;
if(temp==0xb0)
keyvalue=7;
if(temp==0x70)
keyvalue=8;
}
while(temp!=0xf0)//等待松手,很重要
temp=P1&0xf0;//一直检测输入状态
}
P1=0xfb;    //清零P1口第2位,检测
temp=P1&0xf0;
if(temp!=0xf0)
{
delayms(5);  
temp=P1&0xf0;
if(temp!=0xf0)
{
if(temp==0xe0)
keyvalue=9;       //test
if(temp==0xd0)
keyvalue=10;
if(temp==0xb0)
keyvalue=11;
if(temp==0x70)
keyvalue=12;
}
while(temp!=0xf0)//等待松手,很重要
temp=P1&0xf0;//一直检测输入状态
}
P1=0xf7;      //清零P1口第3位,检测
temp=P1&0xf0;
if(temp!=0xf0)
{
delayms(5);  
temp=P1&0xf0;
if(temp!=0xf0)
{
if(temp==0xe0)
keyvalue=13;       //test
if(temp==0xd0)
keyvalue=14;
if(temp==0xb0)
keyvalue=15;
if(temp==0x70)
keyvalue=16;
}
while(temp!=0xf0)//等待松手输入状态
temp=P1&0xf0;//一直检测输入状态
}

return (keyvalue);  //返回键值
}
int main(void)
{
uchar num=1;
P0=0xff;   //作外部输入时要初始化
while(1)
{
 num=keyscan();
 P0=table[num-1];
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值