在keil上实现stc89c52RC单片机如何通过esp8266接收来自串口发送来的数据并显示在lcd1602上的c语言完整代码
时间: 2024-01-22 07:17:41 浏览: 128
以下是在Keil上实现STC89C52RC单片机通过ESP8266接收串口数据并将其显示在LCD1602上的C语言完整代码:
```c
#include <reg52.h>
#include <stdio.h>
#include <string.h>
#include "lcd1602.h"
#define FOSC 11059200L
#define BAUD 9600
#define TIMER_1MS (65536-FOSC/1000)
sbit ESP_RTS = P1^0;
sbit ESP_CTS = P1^1;
sbit ESP_RST = P1^2;
volatile unsigned int Timer1Count;
void Timer1Init()
{
TMOD |= 0x10; //set timer1 as timer mode
TH1 = TIMER_1MS / 256;
TL1 = TIMER_1MS % 256;
EA = 1; //enable global interrupt
ET1 = 1; //enable timer1 interrupt
TR1 = 1; //start timer1
}
void Timer1Handler() interrupt 3
{
TF1 = 0; //clear interrupt flag
TH1 = TIMER_1MS / 256;
TL1 = TIMER_1MS % 256;
Timer1Count++;
}
void DelayMs(unsigned int ms)
{
Timer1Count = 0;
while(Timer1Count < ms);
}
void ESP_SendByte(unsigned char byte)
{
ES = 0; //disable serial interrupt
SBUF = byte;
while(!TI);
TI = 0;
ES = 1; //enable serial interrupt
}
unsigned char ESP_RecvByte()
{
unsigned char byte;
ES = 0; //disable serial interrupt
if(RI)
{
byte = SBUF;
RI = 0;
}
ES = 1; //enable serial interrupt
return byte;
}
void ESP_SendString(char *str)
{
while(*str)
{
ESP_SendByte(*str++);
}
}
void ESP_Reset()
{
ESP_RST = 0;
DelayMs(100);
ESP_RST = 1;
DelayMs(5000);
}
void ESP_Init()
{
ESP_Reset();
ESP_SendString("AT+RST\r\n");
DelayMs(5000);
ESP_SendString("AT+CWMODE=1\r\n");
DelayMs(1000);
ESP_SendString("AT+CWJAP=\"SSID\",\"password\"\r\n");
DelayMs(2000);
}
void main()
{
char buffer[16];
unsigned char recv_byte;
unsigned char recv_index;
unsigned char recv_data[64];
unsigned char recv_flag = 0;
unsigned char i;
TMOD &= 0xF0; //set timer0 as timer mode
TMOD |= 0x01;
TH0 = 0xFC; //10ms
TL0 = 0x67;
ET0 = 1; //enable timer0 interrupt
TR0 = 1; //start timer0
LCD_Init();
ESP_Init();
while(1)
{
if(recv_flag)
{
recv_flag = 0;
if(strcmp(recv_data, "Hello") == 0)
{
LCD_Clear();
LCD_WriteString("Hello World!");
ESP_SendString("OK\r\n");
}
else if(strcmp(recv_data, "Time") == 0)
{
sprintf(buffer, "Time:%d", TH0 * 256 + TL0);
LCD_Clear();
LCD_WriteString(buffer);
ESP_SendString("OK\r\n");
}
memset(recv_data, 0, sizeof(recv_data));
recv_index = 0;
}
if(ESP_RTS == 0 && ESP_CTS == 1)
{
recv_byte = ESP_RecvByte();
recv_data[recv_index++] = recv_byte;
if(recv_byte == '\n')
{
recv_flag = 1;
}
}
}
}
void Timer0Handler() interrupt 1
{
TH0 = 0xFC;
TL0 = 0x67;
LCD_Update();
}
```
在这个代码中,我们使用了STC89C52RC单片机和ESP8266模块。在初始化函数`ESP_Init()`中,我们设置ESP8266连接到Wi-Fi网络,并将其设置为客户端模式。
在主循环中,我们检查`ESP_RTS`和`ESP_CTS`引脚的状态以接收串口数据。当接收到完整的数据包时,我们可以根据其内容在LCD1602上显示相应的信息并回复ESP8266一个“OK”字符串作为确认。
我们还使用了计时器1和计时器0来实现延迟和LCD更新。
请注意,此代码仅是示例代码,您需要根据您的具体硬件和需求进行修改和优化。
阅读全文