基于51单片机的lcd1602两行静态显示代码
时间: 2023-09-01 18:07:28 浏览: 158
LCD1602液晶屏动态显示静态显示移动显示滚动显示C51单片机KEIL工程源码文件.zip
5星 · 资源好评率100%
以下是基于51单片机的LCD1602两行静态显示的代码示例:
```c
#include <reg52.h>
#define LCD_RS P2_0
#define LCD_RW P2_1
#define LCD_EN P2_2
#define LCD_DATA P0
void delay(unsigned int i)
{
while (i--);
}
void LCD_WriteCommand(unsigned char cmd)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_DATA = cmd;
LCD_EN = 1;
delay(100);
LCD_EN = 0;
}
void LCD_WriteData(unsigned char dat)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_DATA = dat;
LCD_EN = 1;
delay(100);
LCD_EN = 0;
}
void LCD_Init(void)
{
LCD_WriteCommand(0x38); // Function set: 8-bit, 2-line, 5x7 dots
LCD_WriteCommand(0x0c); // Display on, cursor off, blink off
LCD_WriteCommand(0x06); // Entry mode set: increment
LCD_WriteCommand(0x01); // Clear display
delay(100);
}
void LCD_WriteString(unsigned char x, unsigned char y, unsigned char *s)
{
unsigned char i = 0;
if (y == 0) {
LCD_WriteCommand(0x80 + x);
} else {
LCD_WriteCommand(0xc0 + x);
}
while (s[i] != '\0') {
LCD_WriteData(s[i]);
i++;
}
}
void main()
{
LCD_Init(); // 初始化LCD
LCD_WriteString(0, 0, "Hello, world!"); // 第一行显示
LCD_WriteString(0, 1, "51 MCU"); // 第二行显示
while (1); // 循环等待
}
```
代码中定义了LCD_RS、LCD_RW、LCD_EN和LCD_DATA等宏,分别对应LCD的RS、RW、EN和DATA引脚。其中LCD_WriteCommand()和LCD_WriteData()函数分别用于向LCD写入指令和数据,LCD_Init()用于初始化LCD,LCD_WriteString()用于在指定位置显示字符串。最后在main函数中调用这些函数实现LCD的初始化和显示。
阅读全文