51单片机按键控制lcd1602代码
时间: 2023-10-07 07:07:06 浏览: 117
基于51单片机的LCD1602控制
以下是51单片机按键控制LCD1602显示的代码:
```c
#include <regx52.h>
#define LCD1602_DB P0
sbit LCD1602_RS = P2^6;
sbit LCD1602_RW = P2^5;
sbit LCD1602_E = P2^7;
void DelayMs(unsigned int x)
{
unsigned char j;
while (x--)
{
for (j = 0; j < 110; j++);
}
}
void LcdWriteCmd(unsigned char cmd)
{
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DB = cmd;
DelayMs(5);
LCD1602_E = 1;
DelayMs(5);
LCD1602_E = 0;
}
void LcdWriteData(unsigned char dat)
{
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DB = dat;
DelayMs(5);
LCD1602_E = 1;
DelayMs(5);
LCD1602_E = 0;
}
void LcdInit()
{
LcdWriteCmd(0x38); //初始化16*2显示模式,5*7点阵,8位数据接口
LcdWriteCmd(0x0c); //开启显示,不显示光标
LcdWriteCmd(0x06); //写入一个字符后地址自动加1
LcdWriteCmd(0x01); //清屏
}
void Display(unsigned char *s)
{
while (*s)
{
LcdWriteData(*s++);
}
}
void main()
{
unsigned char key, flag = 0;
LcdInit();
while (1)
{
key = P3 & 0x0f;
if (key != 0x0f)
{
DelayMs(5);
if (key != 0x0f)
{
switch (key)
{
case 0x07: //按下key1
flag = 1;
break;
case 0x0b: //按下key2
flag = 2;
break;
case 0x0d: //按下key3
flag = 3;
break;
case 0x0e: //按下key4
flag = 4;
break;
}
}
}
if (flag == 1)
{
LcdWriteCmd(0x80); //将光标定位到第一行
Display("Hello, World!");
flag = 0;
}
else if (flag == 2)
{
LcdWriteCmd(0x80); //将光标定位到第一行
Display("Welcome to LCD!");
flag = 0;
}
else if (flag == 3)
{
LcdWriteCmd(0xc0); //将光标定位到第二行
Display("This is 1602 LCD.");
flag = 0;
}
else if (flag == 4)
{
LcdWriteCmd(0xc0); //将光标定位到第二行
Display("Hello, 51 MCU!");
flag = 0;
}
}
}
```
注:以上代码是一个简单的例子,只是在LCD上显示了几个固定的字符串。如果需要进一步开发,可以根据具体需求对代码进行修改。
阅读全文