单片机源程序如下:
- /*读取键盘值(先读行,后读列,两两相加,再来个switch判断,函数返回值0-15)
- --> 若有键按下 P2显示0-f -->判断是否松开按键,没松开等待,松开返回程序
- 起始位置
- */
- #include <reg51.h>
- #include "delay.h"
- #define unit unsigned int
- #define uchar unsigned char
- uchar led[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,
- 0x77,0x7c,0x39,0x5e,0x79,0x71,};//0-f 共阴数码管
- uchar key;
- uchar i,j;
- uchar keycl()//读取键盘的函数(注:子函数最好放在main前,这样就不用申明)
- {
- uchar a,b;
- P1=0x0f;
- i=P1;//读取P1低4位,放在i
- P1=0xf0;
- j=P1;//不用说也知道吧
- a=i+j;//行+列
- switch(a)//16种情况
- {
- case 0x7e:b=0;break;
- case 0xbe:b=1;break;
- case 0xde:b=2;break;
- case 0xee:b=3;break;
- case 0x7d:b=4;break;
- case 0xbd:b=5;break;
- case 0xdd:b=6;break;
- case 0xed:b=7;break;
- case 0x7b:b=8;break;
- case 0xbb:b=9;break;
- case 0xdb:b=10;break;
- case 0xeb:b=11;break;
- case 0x77:b=12;break;
- case 0xb7:b=13;break;
- case 0xd7:b=14;break;
- case 0xe7:b=15;break;
- default:b=0xff ;break;
- }
- return(b);//函数返回值
- }
- void main()
- {
- P2=0x00;//数码管啥都不显示
- while(1)
- {
- key=keycl();//读键盘值,key=函数返回值
- if(key!=0xff)//有键按下么?
- {
- delay(5);
- if(key!=0xff)//真的有么?有的 就继续往下走
- {
-
- P2=led[key];
- while(P1!=0xf0);//你松开了按键么?没就在这等着
- do{delay(5);}
- while(P1!=0xf0);//你真的松开了么?假的就等着
- }
- }
- }
- }
复制代码
所有资料51hei提供下载:
矩阵键盘.zip
(45.33 KB, 下载次数: 40)
|