AVR单片机(ATMEGA16)矩阵键盘扫描程序
扫描二维码
随时随地手机看文章
程序思路与缺陷参考:51单片机(AT89C52)矩阵键盘检测程序
#include
typedef unsigned char uchar;
typedef unsigned int uint;
#define dula_h PORTD|=0x01
#define dula_l PORTD&=0xfe
#define wela_h PORTD|=0x02
#define wela_l PORTD&=0xfd
#define keyport PORTB
#define keypin (PINB)
#define keydre DDRB
#define keystate0 0 //按键确认状态
#define keystate1 1 //按键无动作状态
char keystate=1; //按键状态初始化为按键无动作状态
uchar keynum=0;
void delayms(uint z) //1ms
{
uint x,y;
for(x=z;x>0;x--)
for(y=157;y>0;y--);
}
uchar table[]={ //共阳数码管
0xc0,0xf9,0xa4,0xb0,
0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,
0xc6,0xa1,0x86,0x8e};
void smg(void)
{
dula_l;
wela_l;
PORTC=0x01;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x02;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x04;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x08;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x10;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x20;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x40;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
PORTC=0x80;
wela_h;
wela_l;
PORTC=table[keynum];
dula_h;
dula_l;
delayms(1);
}
void keyscan(void)
{
uchar temp1,temp2,column,row;
switch(keystate)
{
case keystate0: //keystate0,按键按下确认状态,下一状态为keystate1(按键无动作状态)
keydre=0xff;
keyport=0x0f;
keydre=0xf0;
temp1=keypin;
keydre=0xff;
keyport=0xf0;
keydre=0x0f;
temp2=keypin;
if((temp1|temp2)!=0xff)
{
temp1|=temp2;
if(!(temp1&0x80))
row=3;
else
if(!(temp1&0x40))
row=2;
else
if(!(temp1&0x20))
row=1;
else
if(!(temp1&0x10))
row=0;
if(!(temp1&0x08))
column=3;
else
if(!(temp1&0x04))
column=2;
else
if(!(temp1&0x02))
column=1;
else
if(!(temp1&0x01))
column=0;
keynum=column*4+row;
while(!(keyport==0x0f|keyport==0xf0));
keystate=keystate1;
break;
}
else
keystate=keystate1;
break;
case keystate1: //keystate1,按键无动作状态,下一状态为keystate0(按键无动作状态)
keydre=0xff;
keyport=0x0f; //输出0x0f
keydre=0xf0;
temp1=keypin;
keydre=0xff;
keyport=0xf0; //输出0xf0
keydre=0x0f;
temp2=keypin;
if((temp1|temp2)!=0xff)
{
keystate=keystate0;
}
else
keystate=keystate1;
break;
}
}
void main(void)
{
DDRC=0xff;
DDRD|=0x03;
while(1)
{
keyscan();
smg();
}
}