/*P1口外接3*4矩阵键盘,P1^0不用,反转法读键值 本程序虽然稍多几行,但是没有循环, 还可以提前返回,所以执行的速度最快*/ #include<reg52.h> #include<intrins.h> #define uint unsigned int #define uchar unsigned char uchar code table[]={ ~0x3F,~0x06,~0x5B,~0x4F,~0x66, ~0x6D,~0x7D,~0x07,~0x7F,~0x6F, ~0x77,~0x7C,~0x39,~0x5E,~0x79,~0x71};//共阳极LED代码与共阴极正好相反,所以阴极码取反 uchar num; uchar keyscan(); /*void delay(uint z) { uint x,y; for(x=z;x>0;x--) for(y=110;y>0;y--); }*/ void main() { P0=table[0]; while(1) { num=keyscan(); if(num!=16) P0=table[num]; } } uchar keyscan() { uchar temh,teml,key; P1=0xf0;//低四位先输出0 temh=P1;//读入temh,高四位含有按键信息 P1=0x0f;//反转输出0,即高四位输出0 teml=P1;//读入teml,低四位含有按键信息 //------------------ //两次读入的时间间隔,必须尽量小,以尽量避免按键状态发生变化 //要注重这些,有些程序甚至还有间隔几个毫秒的! //按键会抖动,时间长,有可能读出别的 //------------------ switch(temh) { case 0xe0: key=0;break; case 0xd0: key=1;break; case 0xb0: key=2;break; case 0x70: key=3;break; default :return 16;//按下不是上述键,就当没有键 } switch(teml) { //case 0x0e: return key; 如果P1^0不接,此句不执行,key值稍加改变 case 0x0d: return key; case 0x0b: return key+4; case 0x07: return key+8; default :return 16;//按下不是上述键,就当没有键 } }