PIC單片機(jī)矩陣鍵盤檢測(cè)原理及實(shí)現(xiàn)
#include
#define uchar unsigned char
#define uint unsigned int
__CONFIG(0x3B31);
const uchar table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
uchar key_num;
void delay(uint x);
void init();
void scan();
void didi(uchar num);
void disp();
void main()
{
init();
while(1)
{
scan();
disp();
}
}
void delay(uint x)
{
uint a,b;
for(a=x;a>0;a--)
for(b=110;b>0;b--);
}
void init()
{
TRISB=0x0f;
TRISD=0;
TRISA=0;
TRISE0=0;
RE0=0;
PORTD=0;
PORTA=0xff;
}
void scan()
{
uchar key_tem;
PORTB=0x7f;//0111 1111
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
delay(10);
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
key_tem=key_num;
didi(1);
while(key_tem!=0x0f)
{
key_tem=PORTB;
key_tem=key_tem&0x0f;
}
key_num=key_num|0x70;
}
}
else
{
PORTB=0xBf;//1011 1111
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
delay(10);
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
key_tem=key_num;
didi(1);
while(key_tem!=0x0f)
{
key_tem=PORTB;
key_tem=key_tem&0x0f;
}
key_num=key_num|0xb0;
}
}
else
{
PORTB=0xdf;//1101 1111
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
delay(10);
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
key_tem=key_num;
didi(1);
while(key_tem!=0x0f)
{
key_tem=PORTB;
key_tem=key_tem&0x0f;
}
key_num=key_num|0xd0;
}
}
else
{
PORTB=0xef;//1011 1111
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
delay(10);
key_num=PORTB;
key_num=key_num&0x0f;
if(key_num!=0x0f)
{
key_tem=key_num;
didi(1);
while(key_tem!=0x0f)
{
key_tem=PORTB;
key_tem=key_tem&0x0f;
}
key_num=key_num|0xe0;
}
}
}
}
}
}
void disp()
{
switch(key_num)
{
case 0xee:PORTD=table[0];break;//1110
case 0xed:PORTD=table[1];break;//1101
case 0xeb:PORTD=table[2];break;//1011
case 0xe7:PORTD=table[3];break;//0111
case 0xde:PORTD=table[4];break;
case 0xdd:PORTD=table[5];break;
case 0xdb:PORTD=table[6];break;
case 0xd7:PORTD=table[7];break;
case 0xbe:PORTD=table[8];break;
case 0xbd:PORTD=table[9];break;
case 0xbb:PORTD=table[10];break;
case 0xb7:PORTD=table[11];break;
case 0x7e:PORTD=table[12];break;
case 0x7d:PORTD=table[13];break;
case 0x7b:PORTD=table[14];break;
case 0x77:PORTD=table[15];break;
}
}
void didi(uchar num)
{
uchar di_num;
for(di_num=num;di_num>0;di_num--)
{
RE0=1;
delay(50);
RE0=0;
delay(20);
}
}