写一个esp8266连接MQTT服务器的代码
时间: 2024-03-05 11:50:35 浏览: 135
好的,以下是一个简单的ESP8266连接MQTT服务器的代码示例,你可以根据自己的需求进行修改:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi网络信息
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT服务器信息
const char* mqtt_server = "your_MQTT_server";
const char* mqtt_username = "your_MQTT_username";
const char* mqtt_password = "your_MQTT_password";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// 启动串口
Serial.begin(115200);
// 连接WiFi网络
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// 连接MQTT服务器
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT server...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password )) {
Serial.println("Connected to MQTT server");
client.subscribe("your_topic");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println("Retrying 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 in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.println("Reconnecting to MQTT server...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password )) {
Serial.println("Connected to MQTT server");
client.subscribe("your_topic");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println("Retrying in 5 seconds...");
delay(5000);
}
}
}
```
在代码中,你需要替换以下部分:
- `your_SSID`和`your_PASSWORD` 替换为你的WiFi网络名称和密码;
- `your_MQTT_server`、`your_MQTT_username`和`your_MQTT_password`替换为你的MQTT服务器信息;
- `your_topic`替换为你的MQTT主题。
记得在你的Arduino IDE中安装`PubSubClient`库,这是一个MQTT客户端库。
阅读全文