PIC:矩陣鍵盤掃描(if()else嵌套方式)
/*
為自已寫的矩陣鍵盤檢測+數(shù)碼管顯示+蜂鳴器響
采用if().....else嵌套方式;編譯通過,卻后二列顯示不出來(你找出來了嗎?一個不算問題的問題)
*/
//----------------------------------------------------------------
#include pic.h>
#define uint unsigned int
#define uchar unsigned char
__CONFIG(0x3B31);
const unsigned char table[] = {0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,
0x5e,0x79,0x71}; //數(shù)碼管數(shù)組
//--------------------變量定義------------------------------------
uint keynum,keytem,num; //定義變量,//keynum按鍵端口讀回值,keytem為松手檢測值(以示區(qū)分),num數(shù)碼管
//--------------------函數(shù)調(diào)用 聲明-------------------------------
void init(); //初始化函數(shù)
void keyscan(); //矩陣鍵盤掃描
void didi(uchar dinum); //蜂鳴器
void disp(); //數(shù)碼管顯示
//-------------------主函數(shù)---------------------------------------
void delay(x) //延時函數(shù),幾乎每個程序都要用到,所以放在了主函數(shù)分界線內(nèi)
{
uchar a,b;
for (a=x;a>0;a--)
for(b=110;b>0;b--);
}
void main()
{
init(); //初始化
while(1)
{
keyscan(); //矩陣鍵盤掃描
disp(); //數(shù)碼管顯示
}
}
//------------初始化函數(shù)-------------------------------------------
void init()
{
TRISA=0;PORTA=0x02; //38譯碼器
TRISB=1; //矩陣鍵盤
TRISC=0;PORTC=0x01;; //38使能
TRISD=0;PORTD=0x00; //LED燈(數(shù)碼管)
TRISE=0;PORTE=0x00; //蜂鳴器
}
//----------要調(diào)用的函數(shù)--------------------------------------------
void keyscan()
{ //第一列掃描
PORTB=0xef; //送出RB4=1110 1111
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0xef)
{
delay(5);
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0x0f)
{
keytem=keynum;
didi(1);
while(keytem!=0x0f)
{
keytem=PORTB;
keytem=keytem0x0f;
}
keynum=keynum|0xe0;
}
else //第二列掃描
{
PORTB=0xdf;
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0xdf)
{
delay(5);
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0x0f)
{
keytem=keynum;
didi(1);
while(keytem!=0x0f)
{
keytem=PORTB;
keytem=keytem0x0f;
}
keynum=keynum|0xd0;
}
}
else
{
PORTB=0xbf;
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0xbf)
{
delay(5);
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0x0f)
{
keytem=keynum;
didi(1);
while(keytem!=0x0f)
{
keytem=PORTB;
keytem=keytem0x0f;
}
keynum=keynum|0xb0;
}
else //第四列掃描
{
PORTB=0x7f;
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0x7f)
{
delay(5);
keynum=PORTB;
keynum=keynum0x0f;
if(keynum!=0x0f)
{
keytem=keynum;
didi(1);
while(keytem!=0x0f)
{
keytem=PORTB;
keytem=keytem0x0f;
}
keynum=keynum|0x70;
}
}
} ////////
}
}
}
}
}
void didi(uchar dinum)
{
uchar di_num;
for(di_num=dinum;di_num>0;di_num--)
{
RE0=1;
delay(100);
RE0=0;
delay(50);
}
}
void disp()
{
switch(keynum)
{
case 0xee:PORTD=table[1];break;
case 0xed:PORTD=table[2];break;
case 0xeb:PORTD=table[3];break;
case 0xe7:PORTD=table[4];break;
case 0xde:PORTD=table[5];break;
case 0xdd:PORTD=table[6];break;
case 0xdb:PORTD=table[7];break;
case 0xd7:PORTD=table[8];break;
case 0xbe:PORTD=table[9];break;
case 0xbd:PORTD=table[10];break;
case 0xbb:PORTD=table[11];break;
case 0xb7:PORTD=table[12];break;
case 0x7e:PORTD=table[13];break;
case 0x7d:PORTD=table[14];break;
case 0x7b:PORTD=table[15];break;
case 0x77:PORTD=table[0];break;
}
}
評論