arduino mqtt示例
时间: 2023-10-03 11:05:56 浏览: 115
android mqtt样例
4星 · 用户满意度95%
以下是一个简单的Arduino MQTT示例代码:
```
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi连接参数
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT服务器参数
const char* mqtt_server = "your_MQTT_SERVER";
const int mqtt_port = 1883;
const char* mqtt_topic = "your_TOPIC";
// WiFi客户端和MQTT客户端
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// 初始化串口
Serial.begin(9600);
// 连接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);
while (!client.connected()) {
if (client.connect("arduinoClient")) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("Failed to connect to MQTT server, rc=");
Serial.print(client.state());
Serial.println(" retrying...");
delay(1000);
}
}
// 订阅主题
client.subscribe(mqtt_topic);
}
void loop() {
// 检查WiFi连接
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected, reconnecting...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
}
Serial.println("Connected to WiFi");
}
// 检查MQTT连接
if (!client.connected()) {
Serial.println("MQTT disconnected, reconnecting...");
if (client.connect("arduinoClient")) {
Serial.println("Connected to MQTT server");
client.subscribe(mqtt_topic);
} else {
Serial.print("Failed to connect to MQTT server, rc=");
Serial.print(client.state());
Serial.println(" retrying...");
delay(1000);
}
}
// 处理MQTT消息
client.loop();
}
// 订阅消息的回调函数
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Message: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
```
该代码连接到WiFi和MQTT服务器,并订阅一个主题。在循环中,它检查WiFi和MQTT连接,并在需要时重新连接。它还处理MQTT消息并将其打印到串口。您需要将代码中的“your_SSID”,“your_PASSWORD”,“your_MQTT_SERVER”和“your_TOPIC”替换为实际的值。
阅读全文