原理图
- #include<reg52.h>
- #include<stdio.h>
- #include<intrins.h>
- sbit RS = P2^0; //Pin4
- sbit RW = P2^1; //Pin5
- sbit E= P2^2; //Pin6
- #define Data P0//数据端口
- char TimeNum[16];
- char Test1[16];
- void DelayUs(unsigned char us)//微秒级延时函数
- {
- unsigned char uscnt;
- uscnt=us>>1;
- while(--uscnt);
- }
- void DelayMs(unsigned char ms) //毫秒级延时函数
- {
- while(--ms)
- {
- DelayUs(250);
- DelayUs(250);
- DelayUs(250);
- DelayUs(250);
- }
- }
- void WriteCommand(unsigned char c)//写命令函数
- {
- DelayMs(5);//操作前短暂延时,保证信号稳定
- E=0;
- RS=0;
- RW=0;
- _nop_();
- E=1;
- Data=c;
- E=0;
- }
- void WriteData(unsigned char c) //写数据函数
- {
- DelayMs(5);//操作前短暂延时,保证信号稳定
- E=0;
- RS=1;
- RW=0;
- _nop_();
- E=1;
- Data=c;
- E=0;
- RS=0;
- }
- void ShowChar(unsigned char pos,unsigned char c)//写字符函数
- {
- unsigned char p;
- if (pos>=0x10)
- p=pos+0xb0; //是第二行则命令代码高4位为0xc
- else
- p=pos+0x80; //是第二行则命令代码高4位为0x8
- WriteCommand (p);//写命令
- WriteData (c);//写数据
- }
- void lcd_sfm(unsigned char add,unsigned char date)//显示位置和数据
- {
- unsigned char shi,ge;
- shi=date/10;
- ge=date%10;
- WriteCommand(0x80+0x40+add);
- WriteData(0x30+shi);
- WriteData(0x30+ge);
- }
- void ShowString (unsigned char line,char *ptr)//写字符串函数
- {
- unsigned char l,i;
- l=line<<4;//若line=0,则地址的高四位为0;若line=1.则地址的高四位为1
- for (i=0;i<16;i++)
- ShowChar (l++,*(ptr+i));//循环显示16个字符
- }
- void InitLcd()//初始化函数
- {
- DelayMs(15);
- WriteCommand(0x38); //display mode
- WriteCommand(0x38); //display mode
- WriteCommand(0x38); //display mode
- WriteCommand(0x06); //显示光标移动位置
- WriteCommand(0x0c); //显示开及光标设置
- WriteCommand(0x01); //显示清屏
- }
- void delay(unsigned int t)
- {while(t--);
- }
- unsigned char keyscan(void) //矩阵键盘扫描函数
- {
- unsigned char h,l; //定义行、列值中间变量
- P1=0x0f; //列线输出全为0,行为1
- h=P1&0x0f; //读入行线
- if(h!=0x0f) //检测有无按键按下,行不全为1
- { delay(100); //延时去抖
- if(h!=0x0f) //如果确实按下
- {
- h=P1&0x0f; //再次读入行线
- P1=0xf0; //输出当前列线值,行线反转
- l=P1&0xf0; //读入列线值
- return (h+l); //键盘最后组合编码值,也就是键值
- }
- }
- return 0xff; //其余情况返回该值
- }
- unsigned char getkey( )
- {
- unsigned char key,key_num;
- key=keyscan(); //用key读取keyscan()的值
- switch(key)
- { case 0xee: key_num=0; break;
- case 0xed: key_num=1; break;
- case 0xeb: key_num=2; break;
- case 0xe7: key_num=3; break;
- case 0xde: key_num=4; break;
- case 0xdd: key_num=5; break;
- case 0xbd: key_num=6; break;
- case 0x7d: key_num=7; break;
- case 0xbe: key_num=8; break;
- case 0xdb: key_num=9; break;
- case 0xbb: key_num=10; break;
- case 0x7b: key_num=11; break;
- case 0x7e: key_num=12; break;
- case 0xd7: key_num=13; break;
- case 0xb7: key_num=14; break;
- case 0x77: key_num=15; break;
- default:key_num=0xff; break;
- }
- return key_num;
- }
- void main(void)//主函数
- { unsigned char kk;
- float x=99.0;
- InitLcd();//初始化LCD
- DelayMs(15);//延时保证信号稳定
- lcd_sfm(5,43);
- ShowString(0,"LCD");
- while(1)
- { kk=getkey();
- if(kk!=0xff)
- { lcd_sfm(5,kk);
- }
- }
- }
复制代码
|