arduino esp8266 连接mqtt服务器
esp8266连接mqtt服务器教程。
一、PubSubClient库下载
下载链接:PubSubClient.zip
二、导入项目
#include <ESP8266WiFi.h>
#include "PubSubClient.h"
WiFiClient espwifiClient;
// 初始化mqtt
PubSubClient mqttClient(espwifiClient);
void mqtt_callback(char *topic, byte *payload, unsigned int length) {
String msg = "";
for (int i = 0; i < length; i++) {
msg += (char)payload[i];
}
/**
* 消息处理代码
*/
msg = "";
}
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
// 连接wifi
WiFi.begin("ssid", "passwd");
// 等待wifi连接
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("wifi connected!");
// 设置服务器
mqttClient.setServer("abc.com", 8888);
// mqtt消息处理
mqttClient.setCallback(mqtt_callback);
// 连接mqtt
mqttClient.connect("id");
}
void loop() {
// mqtt连接后开启监听
if (mqttClient.connected()) {
mqttClient.loop();
}
}