51单片机4乘4矩阵和1602屏幕的计算器代码.docx
《51单片机4乘4矩阵和1602屏幕的计算器代码.docx》由会员分享,可在线阅读,更多相关《51单片机4乘4矩阵和1602屏幕的计算器代码.docx(8页珍藏版)》请在冰豆网上搜索。
51单片机4乘4矩阵和1602屏幕的计算器代码
51单片机4*4矩阵和1602屏幕的计算器代码
一、要求:
液晶显示器第一行显示“HelloWorld!
”;
第二行显示键值和按键次数,且按键时间大于1.5秒时,识别为2次按键。
单片机型号:
STC--12C5A16AD
二、程序代码:
#include
#include
#defineucharunsignedchar
#defineuintunsignedint
unsignedcharcodedis[]={"HelloWorld!
"};
unsignedcharcodedis1[]={"KEY:
"};
unsignedcharcodedis2[]={"TIME:
"};
ucharkey_val[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G'};
ucharcodekey_code[]={0x77,0x7B,0x7D,0x7E,0xB7,0xBB,0xBD,0xBE,0xD7,0xDB,0xDD,0xDE,0xE7,0xEB,0xED,0xEE};
ucharkey,x,count;
uinttime=0;
sbitU3_DS=P1^5;
sbitU3_STCP=P1^4;
sbitU3_SHCP=P1^3;
sbitU4_DS=P1^2;
sbitU4_STCP=P1^1;
sbitU4_SHCP=P1^0;
voiddelay(unsignedintn);
//74HC595
voidU3_595(unsignedcharnum)
{
unsignedcharcount1;
for(count1=0;count1<=7;count1++)
{
if((num&0x80)==0x80)//最高位为1,则向SDATA_595发送1
{
U3_DS=1;
}
else
{
U3_DS=0;
}
U3_SHCP=0;
U3_SHCP=1;
num<<=1;//左移
}
U3_STCP=0;
U3_STCP=1;
}
voidU4_595(unsignedcharnum)//发送指令到RS,RW,E(4,5,6位)
{
unsignedcharcount2;
for(count2=0;count2<=7;count2++)
{
if((num&0x80)==0x80)
{
U4_DS=1;
}
else
{
U4_DS=0;
}
U4_SHCP=0;
U4_SHCP=1;
num<<=1;
}
U4_STCP=0;
U4_STCP=1;
}
//LCD延时子程序n=1时延时1ms
voiddelay(unsignedintn)
{
unsignedinti;
for(;n>0;n--)
for(i=0;i<255;i++)
_nop_();
}
//写指令到LCD
voidwcmd(unsignedcharcmd)
{
U4_595(0x00);
U3_595(cmd);
U4_595(0x40);
U4_595(0x00);
}
//写要显示的数据到LCD
voidwdat(unsignedchardat)
{
U4_595(0x10);
U3_595(dat);
U4_595(0x50);
U4_595(0x10);
}
//初始化LCD
voidinit()
{
wcmd(0x38);//设置8位总线双行显示,5*7点阵
delay(20);
wcmd(0x0C);//开显示,开光标,不闪烁
delay(20);
wcmd(0x06);//读写字符时地址加1
delay(20);
wcmd(0x01);//清屏
delay(20);
wcmd(0x80+2);
for(x=0;x<12;x++)//第一行显示helloworld!
wdat(dis[x]);
delay(20);
wcmd(0xC2);
for(x=0;x<4;x++)//第二行显示按键和次数
wdat(dis1[x]);
wcmd(0xC8);
for(x=0;x<5;x++)
wdat(dis2[x]);
TMOD=0x01;//中断设置
TH0=0x3C;//定时初值设置
TL0=0xB0;
EA=1;//开中断
ET0=1;//定时器0中断允许
}
//键盘扫描子程序
ucharkeyscan(void)
{
unsignedcharhang,lie,keycode;
chari;
P0=0xf0;
hang=P0;
if((hang&0xf0)!
=0xf0)//有键按下?
{
delay(50);//去抖动
hang=P0;
if((hang&0xf0)!
=0xf0)//有键按下
{
P0=0x0f;
lie=P0;
keycode=hang|lie;//获得键码
for(i=15;i>=0;i--)
{
if(keycode==key_code[i])//查找键码
{
key=i;
return(key);
}
}
}
}
else
{
P0=0xff;//按键弹起则关闭定时器
TR0=0;
count=0;
return(16);
}
}
voidkeydown()//判断按键按下和显示程序
{
P0=0xf0;
if((P0&0xf0)!
=0xf0)
{
TR0=1;//开启定时器
while(P0!
=0xf0)
keyscan();//获得键码
if(count<30)
{
time++;
count=0;
}
else//超过1.5秒计数2次
{
time+=2;
count=0;
}
wcmd(0xC6);//设置键值显示位置
wdat(key_val[16-key]);
wcmd(0xCD);//设置次数显示位置
if(time<10)
wdat(0x30+time);
if(time>9&&time<100)
{
wdat(0x30+time/10);
wdat(0x30+time%10);
}
if(time>99&&time<1000)
{
wdat(0x30+time/100);
wdat(0x30+time/10-(time/100)*10);
wdat(0x30+time%10);
}
}
}
//中断函数
voidtimer()interrupt1
{
TH0=0x3C;
TL0=0xB0;
count++;
}
voidmain(void)
{
init();
for(;;)
{
keydown();
}
}