/*P1口外接3*4矩陣鍵盤,P1^0不用,反轉(zhuǎn)法讀鍵值 本程序雖然稍多幾行,但是沒有循環(huán), 還可以提前返回,所以執(zhí)行的速度最快*/ #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;//反轉(zhuǎn)輸出0,即高四位輸出0 teml=P1;//讀入teml,低四位含有按鍵信息 //------------------ //兩次讀入的時(shí)間間隔,必須盡量小,以盡量避免按鍵狀態(tài)發(fā)生變化 //要注重這些,有些程序甚至還有間隔幾個(gè)毫秒的! //按鍵會抖動,時(shí)間長,有可能讀出別的 //------------------ 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;//按下不是上述鍵,就當(dāng)沒有鍵 } switch(teml) { //case 0x0e: return key; 如果P1^0不接,此句不執(zhí)行,key值稍加改變 case 0x0d: return key; case 0x0b: return key+4; case 0x07: return key+8; default :return 16;//按下不是上述鍵,就當(dāng)沒有鍵 } }