esp8266实现mqtt消息订阅
时间: 2023-11-15 21:06:35 浏览: 23
要使用ESP8266实现MQTT消息订阅,需要完成以下步骤:
1. 安装MQTT库
在Arduino IDE中,打开“库管理器”,搜索并安装“PubSubClient”库。
2. 连接WiFi和MQTT服务器
使用ESP8266连接WiFi和MQTT服务器。在Arduino IDE中,打开“文件”->“示例”->“PubSubClient”->“mqtt_esp8266”,根据自己的WiFi和MQTT服务器信息修改以下代码:
```c++
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "your_MQTT_SERVER";
const char* mqtt_user = "your_MQTT_USER";
const char* mqtt_password = "your_MQTT_PASSWORD";
```
3. 订阅消息
在`setup()`函数中,使用`client.subscribe()`函数订阅MQTT消息。例如,订阅名为“test”的主题:
```c++
void setup() {
// ...
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect("ESP8266Client", mqtt_user, mqtt_password )) {
Serial.println("connected");
client.subscribe("test");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
```
4. 处理消息
在`callback()`函数中,处理接收到的MQTT消息。例如,将消息打印到串口:
```c++
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
```
完整代码示例:
```c++
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "your_MQTT_SERVER";
const char* mqtt_user = "your_MQTT_USER";
const char* mqtt_password = "your_MQTT_PASSWORD";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect("ESP8266Client", mqtt_user, mqtt_password )) {
Serial.println("connected");
client.subscribe("test");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client", mqtt_user, mqtt_password )) {
Serial.println("connected");
client.subscribe("test");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
```
阅读全文