#include <mega8.h>
#define uchar unsigned char
#define uint unsigned int
#define NOP #asm("nop");
#define gewei PORTC.0
#define shiwei PORTC.1
#define LED_Data PORTD
uchar dtab[17]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x73};
void delayms(void)
{
uint i;
for(i=1;i<1140;i++){;}
}
void delaynms(uint n)
{
uint i;
i="0";
while(i<n)
{
delayms();
i++;
}
}
uchar KeyScan(void)
{
uchar key_temp,key_temp1,key;
key_temp=PINB; //读PORTB各引脚电平
key_temp&=0x0f; //00001111
if (key_temp!=0x0f)//第一次判断---00001111
{
delaynms(70);
key_temp=PINB;
key_temp&=0x0f;
if (key_temp!=0x0f)
{
//////////////////////////
switch(key_temp)
{
case 0x07://说明在第一行 0000 0111即 Key1 Key2 Key3 Key4中有一键被按下
DDRB="0x0f";//交换行列扫描,判断所在列 00001111
PORTB="0xf0";//11110000
NOP;
key_temp1=PINB;
key_temp1&=0xf0;
switch(key_temp1)
{
case 0xe0: key="1";break;//1110 0000 K1 PORTB4被拉低
case 0xd0: key="2";break;//1101 0000 K2 PORTB5被拉低
case 0xb0: key="3";break;//1011 0000 K3 PORTB6被拉低
case 0x70: key="4";break;//0111 0000 K4 PORTB7被拉低
}
DDRB="0xf0";PORTB=0x0f;break;//11110000
//....
case 0x0b://0000 1011
DDRB="0x0f";
PORTB="0xf0";
NOP;
key_temp1=PINB;
key_temp1&=0xf0;
switch(key_temp1)
{
case 0xe0: key="5";break;
case 0xd0: key="6";break;
case 0xb0: key="7";break;
case 0x70: key="8";break;
}
DDRB="0xf0";PORTB=0x0f;break;
//....
case 0x0d: //0000 1101
DDRB="0x0f";
PORTB="0xf0";
NOP;
key_temp1=PINB;
key_temp1&=0xf0;
switch(key_temp1)
{
case 0xe0: key="9";break;
case 0xd0: key="10";break;
case 0xb0: key="11";break;
case 0x70: key="12";break;
}
DDRB="0xf0";PORTB=0x0f;break;
//....
case 0x0e://0000 1110
DDRB="0x0f";
PORTB="0xf0";
NOP;
key_temp1=PINB;
key_temp1&=0xf0;
switch(key_temp1)
{
case 0xe0: key="13";break;
case 0xd0: key="14";break;
case 0xb0: key="15";break;
case 0x70: key="16";break;
}
DDRB="0xf0";PORTB=0x0f;break;
//....
default: key="0";break;
}
}
else{key=0;} //end ..if
}
else{key=0;} //end ..if
return key;
}
void main(void)
{
DDRC.0=1;
DDRC.1=1;
DDRD="0xff";
DDRB="0xf0"; //11110000 PORTB7 PORTB6 PORTD5 PORTD4输出;ORTD3ORTD2 PORTD1 PORTD0读入
PORTB="0x0f"; //00001111 0 0 0 0 1 1 1 1
//设置为读入引脚要使其对应的PORT置1方可正确读入
gewei="1";
shiwei="1";
while(1)
{
LED_Data=dtab[KeyScan()];
}
}
用户200418 2009-3-31 17:49