PIC單片機(jī)矩陣鍵盤+線反轉(zhuǎn)法
/*采用行掃描線反轉(zhuǎn)法RAM占用空間較多,因?yàn)橛玫降淖兞勘容^多,
但是程序變得簡潔。
pic單片機(jī)當(dāng)采用線反轉(zhuǎn)法時(shí)端口寄存器要設(shè)置成輸出*/
#include pic.h>__CONFIG(0x3F32); //芯片配置字#define uchar unsigned char #define uint unsigned intvoid delay10ms(uchar x);void beep();void init();uchar j;uchar LED_CODE[]={0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf};uchar KEY_CODE[]={0x36,0x2e,0x1e,0x35,0x2d,0x1d,0x33,0x2b,0x1b};uchar keyscan(){uchar temp1;PORTB=0x07;//將列線置0,行線作為輸入狀態(tài)檢測。temp1=PORTB;//讀回B端口狀態(tài)值if((temp10x07)!=0x07)//不等于0x07表示有按鍵按下{delay10ms(5);//調(diào)用延時(shí)PORTB=0x07;temp1=PORTB;//讀取行值,并保存PORTB=0x38;//線反轉(zhuǎn),行列反轉(zhuǎn)檢測for(j=0;j=9;j++)//循環(huán)查表9次{if((temp1|PORTB)==KEY_CODE[j])//判斷行列值相加后是否等于查表值{return(j);//返回j}} }}void main(){init();//系統(tǒng)初始化PORTD=LED_CODE[9];//上電數(shù)碼管顯示“—”while(1){ PORTB=0x07;if(PORTB!=0x07)//判斷有無按鍵按下有則執(zhí)行按鍵處理程序{keyscan();//調(diào)用掃描子程序PORTD=LED_CODE[j];//顯示對應(yīng)鍵號PORTB=0x07;//重新賦值if(PORTB!=0x07)//再次判斷有無按鍵按下 按下蜂鳴器響一聲{beep(); //調(diào)用蜂鳴器子函數(shù)}while(PORTB!=0x07)//按鍵松手檢測,如果按鍵一直按下關(guān)閉蜂鳴器{RE1=0;delay10ms(1);}}}}void init()//系統(tǒng)初始化程序{TRISB=0;//pic單片機(jī)當(dāng)采用線反轉(zhuǎn)法時(shí)端口寄存器要設(shè)置成輸出TRISD=0;//D端口設(shè)置為輸出TRISA=0;//A端口設(shè)置為輸出TRISE=0;//E端口設(shè)置為輸出PORTA=0;//A端口全部設(shè)置為低電平,位選開放PORTD=0xFF;//D端口全部設(shè)置為高電平,段選關(guān)閉數(shù)碼管不亮。RE1=0;//蜂鳴器關(guān)閉}void delay10ms(uchar x){uint j,h;for(j=0;jx;j++)for(h=0;h625;h++);}void beep(){RE1=1;delay10ms(10);RE1=0;delay10ms(10);}
評論