AT89C51单片机中,如何实现通过串口通信从PC获得数据直接显示在LCD1602屏幕上,给出一份示范代码。
时间: 2023-03-07 22:13:38 浏览: 132
可以使用下面的示范代码来实现:#include <reg51.h>
#include <stdio.h>
#include <string.h> //定义AT89C51串口发送函数
void UART_SendByte(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
} //定义AT89C51串口接收函数
unsigned char UART_ReceiveByte(void)
{
while(!RI);
RI = 0;
return SBUF;
} //定义1602 LCD引脚
sbit RS = P3^7;
sbit RW = P3^6;
sbit E = P3^5; //定义LCD1602数据引脚
unsigned char LCD_Port = 0x90; //定义LCD1602控制函数
void LCD_WrCmd(unsigned char cmd)
{
RS = 0;
RW = 0;
E = 1;
P2 = cmd;
E = 0;
} //定义LCD1602写数据函数
void LCD_WrDat(unsigned char dat)
{
RS = 1;
RW = 0;
E = 1;
P2 = dat;
E = 0;
} //定义LCD1602初始化函数
void LCD_Init(void)
{
LCD_WrCmd(0x38);
LCD_WrCmd(0x0c);
LCD_WrCmd(0x06);
LCD_WrCmd(0x01);
} //定义LCD1602显示函数
void LCD_Display(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char addr;
if(y == 1)
{
addr = 0x80 + x;
}
else
{
addr = 0xc0 + x;
}
LCD_WrCmd(addr);
while(*str != '\0')
{
LCD_WrDat(*str);
str++;
}
} //定义主函数
void main()
{
unsigned char i,j, k;
unsigned char buff[20]; //初始化LCD1602
LCD_Init(); //串口初始化
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
TR1 = 1; //接收数据,显示在LCD1602上
while(1)
{
k = UART_ReceiveByte();
buff[i] = k;
if(k == '\r')
{
buff[i] = '\0';
LCD_Display(0, 0, buff);
i = 0;
}
else
{
i++;
}
for(j=0; j<i; j++)
{
UART_SendByte(buff[j]);
}
}
}
阅读全文