51单片机串行口实现数据在lcd上显示代码
时间: 2024-03-14 15:43:57 浏览: 14
以下是51单片机串行口实现数据在LCD上显示的代码,代码中使用的是STC89C52单片机和LCD1602液晶屏:
```c
#include <reg52.h>
#include <stdio.h>
#define LCD1602_RS P2_0 // LCD1602的RS引脚
#define LCD1602_RW P2_1 // LCD1602的RW引脚
#define LCD1602_EN P2_2 // LCD1602的EN引脚
#define LCD1602_DATAPINS P0 // LCD1602的数据引脚
sbit UART_RXD = P3^0; // 串口接收引脚
sbit UART_TXD = P3^1; // 串口发送引脚
void init_uart() // 初始化串口
{
TMOD |= 0x20; // 设置定时器1为模式2
TH1 = 0xfd; // 设置波特率为9600
TL1 = 0xfd;
TR1 = 1; // 启动定时器1
SCON = 0x50; // 串口工作在模式1
ES = 1; // 开启串口中断
EA = 1; // 开启总中断
}
void init_lcd() // 初始化LCD
{
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_EN = 0;
delay_ms(15);
lcd_write_cmd(0x38); // 设置LCD为16x2的显示模式
delay_ms(5);
lcd_write_cmd(0x0c); // 开启LCD显示
delay_ms(5);
lcd_clear(); // 清屏
lcd_write_cmd(0x06); // 设置光标自动右移
}
void lcd_write_cmd(unsigned char cmd) // 写指令到LCD
{
LCD1602_RS = 0;
LCD1602_DATAPINS = cmd;
LCD1602_EN = 1;
delay_us(2);
LCD1602_EN = 0;
delay_ms(1);
}
void lcd_write_data(unsigned char dat) // 写数据到LCD
{
LCD1602_RS = 1;
LCD1602_DATAPINS = dat;
LCD1602_EN = 1;
delay_us(2);
LCD1602_EN = 0;
delay_ms(1);
}
void lcd_clear() // 清屏
{
lcd_write_cmd(0x01);
}
void lcd_set_cursor(unsigned char x, unsigned char y) // 设置光标位置
{
unsigned char addr;
if (y == 0)
addr = 0x80 + x;
else
addr = 0xc0 + x;
lcd_write_cmd(addr);
}
void lcd_puts(unsigned char x, unsigned char y, unsigned char *str) // 在指定位置显示字符串
{
lcd_set_cursor(x, y);
while (*str != '\0')
{
lcd_write_data(*str);
str++;
}
}
void uart_isr() interrupt 4 // 串口中断服务程序
{
if (RI)
{
RI = 0;
lcd_write_data(SBUF); // 将接收到的数据写到LCD上
}
}
void main()
{
init_uart();
init_lcd();
while (1);
}
```
上面的代码中,使用了串口中断来接收数据,并将接收到的数据写到LCD上。在主函数中,我们只需要调用初始化函数即可开始使用。在需要发送数据时,只需要通过串口发送即可,数据会自动显示在LCD上。