STC89C52 ESP-01 MQTT 订阅消息 C语言代码
时间: 2023-11-29 10:57:15 浏览: 88
azure-umqtt-c:通用库,用于通过mqtt协议进行通信
以下是STC89C52与ESP8266 ESP-01模块通过MQTT协议进行订阅消息的C语言代码:
```c
#include "reg52.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define uchar unsigned char
#define uint unsigned int
sbit LED=P0^0; //LED灯连接P0.0口
//串口波特率设置
#define BAUD 9600
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1ms定时器计数值
//MQTT服务器地址和端口
#define SERVER_IP "192.168.1.100"
#define SERVER_PORT 1883
//订阅的主题
#define TOPIC "/test/topic"
//ESP8266模块发送AT指令的函数
void esp8266_cmd(char* cmd)
{
char buf[100];
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s\r\n", cmd);
printf("%s", buf);
while(1)
{
if(strstr(buf, "OK") || strstr(buf, "ERROR"))
return;
if(SBUF != 0)
buf[strlen(buf)] = SBUF;
}
}
//连接MQTT服务器
void mqtt_connect()
{
char cmd[100];
//发送MQTT连接请求
sprintf(cmd, "AT+CIPSTART=\"TCP\",\"%s\",%d\r\n", SERVER_IP, SERVER_PORT);
esp8266_cmd(cmd);
sprintf(cmd, "AT+CIPSEND=%d\r\n", 34 + strlen(TOPIC));
esp8266_cmd(cmd);
printf("0104000000064d5154540402001e0004");
printf("%02x", strlen(TOPIC) >> 8);
printf("%02x", strlen(TOPIC) & 0xff);
printf("%s", TOPIC);
while(1)
{
if(strstr(cmd, "SEND OK"))
break;
}
}
//订阅主题
void mqtt_subscribe()
{
char cmd[100];
sprintf(cmd, "AT+CIPSEND=%d\r\n", 35 + strlen(TOPIC));
esp8266_cmd(cmd);
printf("8205");
printf("%02x", strlen(TOPIC) >> 8);
printf("%02x", strlen(TOPIC) & 0xff);
printf("%s", TOPIC);
printf("00");
while(1)
{
if(strstr(cmd, "SEND OK"))
break;
}
}
//处理接收到的MQTT消息
void mqtt_process(char* msg)
{
if(strstr(msg, "ON"))
LED = 0;
else if(strstr(msg, "OFF"))
LED = 1;
}
//接收串口数据中断处理函数
void serial_isr() interrupt 4
{
if(RI == 1)
{
RI = 0;
SBUF = P0;
if(SBUF == '+')
{
char buf[100];
memset(buf, 0, sizeof(buf));
uint i = 0;
while(1)
{
if(SBUF != 0)
{
buf[i++] = SBUF;
if(i >= sizeof(buf))
break;
if(strstr(buf, "OK") || strstr(buf, "ERROR"))
break;
}
}
if(strstr(buf, TOPIC))
{
char msg[100];
memset(msg, 0, sizeof(msg));
uint j = 0;
while(SBUF != 0)
{
msg[j++] = SBUF;
if(j >= sizeof(msg))
break;
}
mqtt_process(msg);
}
}
}
}
//定时器1中断处理函数
void timer1_isr() interrupt 3
{
static uint cnt = 0;
TH1 = T1MS >> 8;
TL1 = T1MS & 0xff;
if(++cnt >= 1000)
{
cnt = 0;
LED = !LED;
}
}
//主函数
void main()
{
//串口初始化
TMOD = 0x20;
TH1 = T1MS >> 8;
TL1 = T1MS & 0xff;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
ES = 1;
EA = 1;
//连接WiFi热点
esp8266_cmd("AT+CWMODE=1");
esp8266_cmd("AT+CWJAP=\"ssid\",\"password\"");
//连接MQTT服务器并订阅主题
mqtt_connect();
mqtt_subscribe();
//循环等待接收MQTT消息
while(1);
}
```
需要注意的是,上述代码需要在STC89C52的环境下编译运行,且需要将ESP8266 ESP-01模块与STC89C52通过串口连接,同时需要将LED灯连接到P0.0口。另外,代码中的MQTT服务器地址、端口和订阅的主题需要根据实际情况进行修改。
阅读全文