基于c51单片机实现通过电脑串口向LCD1602发送数据并显示的代码
时间: 2023-06-27 12:05:47 浏览: 311
以下是基于C51单片机实现通过电脑串口向LCD1602发送数据并显示的代码:
```c
#include <reg51.h>
#define LCD_DB P0
sbit LCD_RS = P2^0;
sbit LCD_EN = P2^1;
void delay(unsigned int i)
{
while(i--);
}
void LCD_init()
{
delay(15000);
LCD_RS = 0;
LCD_EN = 0;
LCD_DB = 0x38;
LCD_EN = 1;
LCD_EN = 0;
delay(5000);
LCD_DB = 0x0C;
LCD_EN = 1;
LCD_EN = 0;
delay(5000);
LCD_DB = 0x01;
LCD_EN = 1;
LCD_EN = 0;
delay(5000);
LCD_DB = 0x06;
LCD_EN = 1;
LCD_EN = 0;
}
void LCD_write_cmd(unsigned char cmd)
{
LCD_RS = 0;
LCD_EN = 0;
LCD_DB = cmd;
LCD_EN = 1;
LCD_EN = 0;
}
void LCD_write_data(unsigned char dat)
{
LCD_RS = 1;
LCD_EN = 0;
LCD_DB = dat;
LCD_EN = 1;
LCD_EN = 0;
}
void LCD_write_string(unsigned char x, unsigned char y, unsigned char *s)
{
unsigned char i = 0;
if(x < 16)
{
LCD_write_cmd(0x80 + y*0x40 + x);
}
else
{
LCD_write_cmd(0x80 + y*0x40 + x - 16);
}
while(s[i] != '\0')
{
LCD_write_data(s[i]);
i++;
}
}
void UART_init()
{
TMOD |= 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
EA = 1;
ES = 1;
}
void UART_interrupt() interrupt 4
{
if(RI)
{
RI = 0;
LCD_write_data(SBUF);
}
if(TI)
{
TI = 0;
}
}
void main()
{
LCD_init();
UART_init();
while(1)
{
LCD_write_string(0, 0, "Serial Port Test");
LCD_write_string(0, 1, "Data: ");
}
}
```
其中,使用P0口作为LCD1602的数据口,使用P2.0和P2.1口作为LCD1602的控制口,使用Timer1作为波特率发生器,使用中断实现接收和发送数据。在UART_interrupt()函数中,RI表示接收到数据,TI表示发送数据完成。在主函数中,通过LCD_write_string()函数向LCD1602上显示字符串。
阅读全文