这个程序,用来扫描4*4的矩阵键盘,并把得到的键值,显示在数码管上.也是非常有用的一段代码.
代码如下:
#include <mega16.h>
#define uchar unsigned char
#define uint unsigned int
uchar right=1;//for key_scan variable
void delay(unsigned char time)//delay function
{
unsigned char b;
for(;time>0;time--)
for(b=50;b>0;b--);
}
//digital number display function, the first parameter is the number you want to show
//the second parameter is the position of the number
void display(unsigned char number,unsigned char position);
unsigned char key_scan();
void systeminit()//a simple system initialization function
{
DDRA=0Xff;//set PORTA output
PORTA=0XFF;//set PORTA output in high level
}
void main(void)
{
unsigned char b1,b2;
uchar key;
unsigned char t=0;
systeminit();
while(1)
{
key=key_scan();
if(key!=16)t=key;
b1=t%10;display(b1,8);delay(5);
b2=(t/10)%10;display(b2,7);delay(5);
}
}
//this function support icc and code vision avr
void display(unsigned char number,unsigned char position)//digtial show function
{
DDRA=0Xff;//set PORTA output
 ORTA=0XFF;//set PORTA output in high level
switch(position)//choice the position
{
case 1:{PORTA&=0xf8;break;}
case 2:{PORTA&=0xf9;break;}
case 3:{PORTA&=0Xfa;break;}
case 4:{PORTA&=0Xfb;break;}
case 5:{PORTA&=0Xfc;break;}
case 6:{PORTA&=0Xfd;break;}
case 7:{PORTA&=0Xfe;break;}
case 8:{PORTA&=0Xff;break;}
}
switch(number)//show number
{
case 0:{PORTA&=0x87;break;} //0
case 1:{PORTA&=0x8f;break;} //1
case 2:{PORTA&=0x97;break;} //2
case 3:{PORTA&=0x9f;break;} //3
case 4:{PORTA&=0xa7;break;} //4
case 5:{PORTA&=0xaf;break;} //5
case 6:{PORTA&=0xb7;break;} //6
case 7:{PORTA&=0xbf;break;} //7
case 8:{PORTA&=0xc7;break;} //8
case 9:{PORTA&=0xcf;break;} //9
default:{PORTA=0xff;break;} //null
}
}
//this function support icc and code vision avr
unsigned char key_scan() //check if key pressed
{
uchar juder;
uchar which; //scan which row
uchar juder1=0; //juder whether key-press undo
DDRD=0X0F;//set low 4 output high 4 input
PORTD=0XFF;//output high leve
for(which=0;which<4;which++)
{
juder=0;
switch(which)//choice key row
{
case 0:{PORTD=0Xfe;break;} //11111110
case 1:{PORTD=0Xfd;break;} //11111101
case 2:{PORTD=0Xfb;break;} //11111011
case 3:{PORTD=0Xf7;break;} //11110111
}
if(right)//get key number
{
while((PIND&0x80)==0)
{
juder++;
if(juder>250){right=0;return(0+4*which);}
}
juder=0;
while((PIND&0x40)==0)
{
juder++;
if(juder>250){right=0;return(1+4*which);}
}
juder=0;
while((PIND&0x20)==0)
{
juder++;
if(juder>250){right=0;return(2+4*which);}
}
juder=0;
while((PIND&0x10)==0)
{
juder++;
if(juder>250){right=0;return(3+4*which);}
}
}
else if((PIND&0x10)!=0&&(PIND&0x20)!=0&&(PIND&0x40)!=0&&(PIND&0x80)!=0)juder1++;
else delay(1);//compensate
}
if(juder1==4)right=1;//make sure every time variable change only one time
return 16;//if no key pull down return 16
} |