这段代码是在单片机中使用串口接收数据后,将数据显示在 LCD 上的一个示例
时间: 2024-03-10 14:49:03 浏览: 140
好的,这是一个单片机的示例代码,使用串口接收数据并将数据显示在LCD上,你可以参考这个代码:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;
void delayms(uint xms) // 延时函数
{
uint i, j;
for(i = xms; i > 0; i--)
for(j = 112; j > 0; j--);
}
void LCD_Wait_Ready() //等待LCD就绪函数
{
uchar sta;
RS = 0;
RW = 1;
do
{
EN = 1;
sta = P0;
EN = 0;
} while(sta & 0x80);
}
void LCD_Write_Com(uchar com) //写命令函数
{
LCD_Wait_Ready();
RS = 0;
RW = 0;
P0 = com;
EN = 1;
EN = 0;
}
void LCD_Write_Data(uchar dat) //写数据函数
{
LCD_Wait_Ready();
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
EN = 0;
}
void LCD_Init() //LCD初始化函数
{
LCD_Write_Com(0x38);
delayms(5);
LCD_Write_Com(0x38);
delayms(5);
LCD_Write_Com(0x38);
delayms(5);
LCD_Write_Com(0x08);
delayms(5);
LCD_Write_Com(0x01);
delayms(5);
LCD_Write_Com(0x06);
delayms(5);
LCD_Write_Com(0x0c);
delayms(5);
}
void main()
{
uchar c;
EA = 1; //开总中断
ES = 1; //开串口中断
TMOD = 0x20; //设置定时器1为8位自动重载
TH1 = 0xfd; //波特率2400
TL1 = 0xfd;
TR1 = 1; //启动定时器1
SCON = 0x50; //设置串口为工作方式1,允许接收
LCD_Init(); //LCD初始化
while(1)
{
LCD_Write_Com(0x01); //清屏
delayms(5);
LCD_Write_Com(0x80); //第一行
delayms(5);
for(c = 0; c < 16; c++)
{
LCD_Write_Data(SBUF); //将串口接收到的数据显示在LCD上
while(!TI); //等待发送完成
TI = 0; //发送完成
}
LCD_Write_Com(0xc0); //第二行
delayms(5);
for(c = 0; c < 16; c++)
{
LCD_Write_Data(SBUF); //将串口接收到的数据显示在LCD上
while(!TI); //等待发送完成
TI = 0; //发送完成
}
delayms(200); //延时
}
}
void ser() interrupt 4 //串口中断函数
{
RI = 0; //清中断标志位
}
```
这段代码使用了51单片机,通过串口接收数据,并将数据显示在LCD上。其中,`LCD_Init()`函数是LCD的初始化函数,`LCD_Write_Com()`函数是写命令函数,`LCD_Write_Data()`函数是写数据函数,`LCD_Wait_Ready()`函数是等待LCD就绪函数,`delayms()`函数是延时函数。
在主函数中,首先开启总中断和串口中断,设置波特率为2400,然后对LCD进行初始化。接着,使用循环将接收到的数据显示在LCD上,并且每次输出16个字符。最后,延时200ms并重复执行循环,以不断接收数据并显示。
需要注意的是,在串口中断函数中,需要清除中断标志位。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)