这是在矩阵键盘1位数码管显示键值0~F的程序上改的,6位数码管显示,只能保存6次键值,超出6次前面的溢出。
#include <AT89X52.H>
#define uint unsigned int //宏定义无符号整型数据
#define uchar unsigned char //宏定义无符号字符型数据
sbit dula=P2^6; //数码管段锁存
sbit wela=P2^7; //数码管位锁存
uchar code table[]={ //共阴数码管(0~F.-)
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71,0x80,0x40};
uchar key=17,key1=17,key2=17,key3=17,key4=17,key5=17,key6=17;
void keyscan() //按键扫描程序
{
static bit sign=0; //按键有效标志
static uint count=0; //消抖计数变量
uchar num=0; //临时变量
P3=0xf0; //赋值P3 1111 0000
if(P3!=0xf0) //检测按键按下并有效
{
count++; //消抖计数
if((count>=500)&&(sign==0)) //100~1000,根据主循环周期调整约10~20ms
{ //按键有效标志0
sign=1; //按键有效标志置1
num=P3; //保存P3值xxxx 0000,x为0或1
num|=0x0f; //保存num按位或0x0f值xxxx 1111
P3=num; //赋值P3 xxxx 1111
num=P3; //保存P3值xxxx xxxx
switch(num)
{
case 0xee: key= 0; break;
case 0xde: key= 1; break;
case 0xbe: key= 2; break;
case 0x7e: key= 3; break;
case 0xed: key= 4; break;
case 0xdd: key= 5; break;
case 0xbd: key= 6; break;
case 0x7d: key= 7; break;
case 0xeb: key= 8; break;
case 0xdb: key= 9; break;
case 0xbb: key=10; break;
case 0x7b: key=11; break;
case 0xe7: key=12; break;
case 0xd7: key=13; break;
case 0xb7: key=14; break;
case 0x77: key=15; break;
}
key6=key5;key5=key4;key4=key3;//转移保存键值
key3=key2;key2=key1;key1=key;
}
}
else //键抬起
{
sign=0; //按键有效标志清0
count=0; //消抖计数清0
}
}
void Timer0Init() //2毫秒@11.0592MHz
{
TMOD= 0x01; //设置定时器模式
TL0 = 0xCD; //设置定时初值
TH0 = 0xF8; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
EA=1; //开总中断
ET0=1; //开定时器0中断
}
void display()
{
static uchar count=0; //计数变量
switch(count)
{
case 0:
P0=table[key6];
dula=1;
dula=0;
P0=0x7e;
wela=1;
wela=0;
count++;
break;
case 1:
P0=table[key5];
dula=1;
dula=0;
P0=0x7d;
wela=1;
wela=0;
count++;
break;
case 2:
P0=table[key4];
dula=1;
dula=0;
P0=0x7b;
wela=1;
wela=0;
count++;
break;
case 3:
P0=table[key3];
dula=1;
dula=0;
P0=0x77;
wela=1;
wela=0;
count++;
break;
case 4:
P0=table[key2];
dula=1;
dula=0;
P0=0xef;
wela=1;
wela=0;
count++;
break;
case 5:
P0=table[key1];
dula=1;
dula=0;
P0=0xdf;
wela=1;
wela=0;
count=0;
break;
}
}
void main() //主函数
{
Timer0Init();
while(1)
{
keyscan(); //按键扫描程序
// display(); //1位数码管显示程序
}
}
void timer0() interrupt 1
{
TL0 = 0xCD; //设置定时初值
TH0 = 0xF8; //设置定时初值
display(); //6位数码管显示程序
} |