51单片机串行口实现数据在lcd上显示代码
时间: 2024-03-16 19:43:30 浏览: 18
好的,以下是51单片机串口通信并将接收到的数据显示在LCD上的简单示例代码:
```c
#include <reg51.h>
#define LCD_RS P2_0
#define LCD_RW P2_1
#define LCD_EN P2_2
#define LCD_DAT P0
void lcd_init()
{
LCD_RS = 0;
LCD_RW = 0;
LCD_EN = 0;
LCD_DAT = 0x38;
LCD_EN = 1;
LCD_EN = 0;
LCD_DAT = 0x0c;
LCD_EN = 1;
LCD_EN = 0;
LCD_DAT = 0x06;
LCD_EN = 1;
LCD_EN = 0;
LCD_DAT = 0x01;
LCD_EN = 1;
LCD_EN = 0;
}
void lcd_write_byte(unsigned char data, unsigned char rs)
{
LCD_RS = rs;
LCD_RW = 0;
LCD_DAT = data;
LCD_EN = 1;
LCD_EN = 0;
}
void lcd_write_str(unsigned char *str)
{
while (*str != '\0')
{
lcd_write_byte(*str, 1);
str++;
}
}
void uart_init()
{
SCON = 0x50; // 8位数据,波特率可变,允许接收
TMOD = 0x20; // 定时器1,工作模式2
TH1 = 0xfd; // 波特率为9600,计算公式:TH1 = 256 - Fosc / 32 / 12 / 波特率
TL1 = 0xfd; // 波特率为9600
TR1 = 1; // 启动定时器1
ES = 1; // 使能串口中断
EA = 1; // 使能总中断
}
void uart_isr() interrupt 4
{
if (RI)
{
RI = 0;
lcd_write_byte(SBUF, 1);
}
}
void main()
{
lcd_init();
uart_init();
while (1)
{
// do nothing
}
}
```
这个代码主要是通过中断方式接收串口数据,并将接收到的数据写入到LCD中进行显示。在代码中,我们使用了P0口连接LCD模块,P2口连接了RS、RW和EN控制线,同时使用了串口中断接收数据。