attachment download/******整版测试1:数码管+矩阵键盘+流水灯*****/
/*现象:按下4*4矩阵键盘,8位数码管显示相应的按键值
同时取余后点亮相应的LED*/
/****作者:爱因斯尼@SCUT***/
/****时间:2010.08.29******/
/***必要的头文件和宏定义***/
#include<reg52.h>//51单片机的头文件
#define uint unsigned int//两个常用的宏定义
#define uchar unsigned char
sbit duan=P1^5;//定义段选端
sbit wei=P1^6;//定义位选端
sbit lie=P1^7;//点阵的列扫描
/***数码管字模,放在程序的代码区***/
uchar code SMG[]={
0xfc,0x60,0xda,0xf2,//0,1,2,3,
0x66,0xb6,0xbe,0xe0, //4,5,6,7,
0xfe,0xf6,0xee,0x3e, //8,9,A,b,
0x9c,0x7a,0x9e,0x8E,0x01};//C,d,E,F
/*********带形参的延时子函数***************/
void delay_ms(uint ms)//毫秒级别
{uint i,j;
for(i=0;i<ms;i++)
for(j=0;j<141;j++);
}
/*********带形参的延时子函数***************/
void delay(uint m)
{uint i,j;
for(i=0;i<m;i++)
for(j=0;j<1148;j++); }
/*********数码管的初始化函数***************/
void Init_smg()
{
P0=0x00;
duan=1;
P0=0x00;//关段选端
duan=0;
P0=0xff;
wei=1;
P0=0xff;//关位选端
wei=0;
lie=1;
P0=0xff;//点阵全灭
lie=0;
}
/****带两个形参的数码管显示子函数****/
void show_smg(uchar num,uchar awei)
{
uchar A=0x80;//这个主要是为了后面的循环移位
P0=0x00;
duan=1; //开段选端
P0=SMG[num];//送段选
duan=0; //关段选端
P0=0xff;
wei=1; //开位选端
P0=~(A>>awei);//送位选
wei=0; //关位选端
delay_ms(1); //稍微延时一下,防止残影
}
/******键盘扫描******/
uchar scan_key()//逐行扫描
{uchar key,pin;
/***第一行***/
P2=0xfe;
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{delay(2);
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{pin=P2;
switch(pin)
{case 0xee:key=1;break;
case 0xde:key=2;break;
case 0xbe:key=3;break;
case 0x7e:key=4;break;
default:key=0;
}
while(pin!=0xf0) //是否释放按键?
{pin=P2;
pin=pin&0xf0;}
}}
/***第二行***/
P2=0xfd;
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{delay(2);
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{pin=P2;
switch(pin)
{case 0xed:key=5;break;
case 0xdd:key=6;break;
case 0xbd:key=7;break;
case 0x7d:key=8;break;
default:key=0;
}
while(pin!=0xf0) //是否释放按键?
{pin=P2;
pin=pin&0xf0;}
}}
/***第三行***/
P2=0xfb;
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{delay(2);
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{pin=P2;
switch(pin)
{case 0xeb:key=9;break;
case 0xdb:key=10;break;
case 0xbb:key=11;break;
case 0x7b:key=12;break;
default:key=0;
}
while(pin!=0xf0) //是否释放按键?
{pin=P2;
pin=pin&0xf0;}
}}
/***第四行***/
P2=0xf7;
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{delay(2);
pin=P2;
pin=pin&0xf0;
while(pin!=0xf0)
{pin=P2;
switch(pin)
{case 0xe7:key=13;break;
case 0xd7:key=14;break;
case 0xb7:key=15;break;
case 0x77:key=16;break;
default:key=0;
}
while(pin!=0xf0) //是否释放按键?
{pin=P2;
pin=pin&0xf0;}
}}
return key-1;
}
/***显示键值的子函数***/
void disp_key()
{
show_smg(scan_key(),0);
show_smg(scan_key(),1);
show_smg(scan_key(),2);
show_smg(scan_key(),3);
show_smg(scan_key(),4);
show_smg(scan_key(),5);
show_smg(scan_key(),6);
show_smg(scan_key(),7);
}
/***主函数***/
void main()
{//uchar get_key;
P2=0x0f;
Init_smg();
while(1)
{//get_key=scan_key();
disp_key();
P3=(0xfe<<(scan_key()%8));//LED的移动
}
}
欢迎光临我们的淘宝网店:http://item.taobao.com/auction/item_detail.htm?item_num_id=9447334857
文章评论(0条评论)
登录后参与讨论