51单片机串行口实现数据在lcd上显示代码
时间: 2024-03-14 09:45:30 浏览: 62
51单片机串口数据发送,LCD显示
以下是基于51单片机串行口实现数据在LCD上显示的代码示例:
```c
#include <reg51.h>
#define LCD_DB P0
sbit LCD_RS = P2^0;
sbit LCD_RW = P2^1;
sbit LCD_EN = P2^2;
void init_lcd();
void write_command(unsigned char command);
void write_data(unsigned char data);
void display_string(unsigned char x, unsigned char y, unsigned char *string);
void delay(unsigned int i);
void main()
{
unsigned char i;
unsigned char data_buffer[16] = "Hello, World!";
init_lcd();
display_string(0, 0, data_buffer);
// 开启串行口
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
while(1)
{
// 等待串行口接收到数据
while(RI == 0);
RI = 0;
// 将接收到的数据存入数据缓冲区
data_buffer[0] = SBUF;
// 在LCD上显示数据
display_string(0, 0, data_buffer);
}
}
void init_lcd()
{
write_command(0x38); // 功能设定:8位数据线,2行显示,5x7点阵字符
write_command(0x0C); // 显示开关:开显示,关光标,不闪烁
write_command(0x06); // 光标移动:写入字符后,光标右移,不移动屏幕
write_command(0x01); // 显示清除:清除屏幕,光标回到起始位置
delay(10); // 等待10毫秒
}
void write_command(unsigned char command)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_DB = command;
LCD_EN = 1;
delay(5);
LCD_EN = 0;
}
void write_data(unsigned char data)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_DB = data;
LCD_EN = 1;
delay(5);
LCD_EN = 0;
}
void display_string(unsigned char x, unsigned char y, unsigned char *string)
{
unsigned char i;
if(x < 16)
{
if(y == 0)
{
write_command(0x80 + x);
}
else if(y == 1)
{
write_command(0xC0 + x);
}
else
{
return;
}
}
else
{
return;
}
for(i = 0; string[i] != '\0' && i < 16 - x; i++)
{
write_data(string[i]);
}
}
void delay(unsigned int i)
{
unsigned int j, k;
for(j = 0; j < i; j++)
{
for(k = 0; k < 1000; k++);
}
}
```
这段代码实现了将串行口接收到的数据显示在LCD上。首先初始化LCD,然后开启串行口,并在主循环中等待串行口接收到数据。当接收到数据后,将数据存入数据缓冲区中,并在LCD上显示数据。其中,`init_lcd()`函数用于初始化LCD,`write_command()`函数用于写入LCD指令,`write_data()`函数用于写入LCD数据,`display_string()`函数用于在LCD上显示字符串。最后,`delay()`函数用于延时。
阅读全文