Arduino ESP32向EMQX发布消息的代码
时间: 2023-06-09 14:07:33 浏览: 95
esp32与EMQX Cloud通讯代码
好的,以下是Arduino ESP32向EMQX发布消息的代码:
```c++
#include <WiFi.h>
#include <PubSubClient.h>
// 连接到Wi-Fi网络
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiClient espClient;
PubSubClient client(espClient);
const char* mqtt_server = "your_MQTT_broker_address";
void setup() {
Serial.begin(115200);
Serial.println("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// 连接到MQTT broker
client.setServer(mqtt_server, 1883);
while (!client.connected()) {
Serial.println("Connecting to MQTT Broker...");
if (client.connect("ESP32Client")) {
Serial.println("MQTT Broker Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
// 发布消息
char message[50];
snprintf (message, 50, "Hello from ESP32");
client.publish("testTopic", message);
delay(1000);
}
```
请注意,你需要修改代码中的 `your_SSID` , `your_PASSWORD` 和 `your_MQTT_broker_address` 分别为你的Wi-Fi SSID,Wi-Fi密码和MQTT broker的ip地址或域名。还需要安装 PubSubClient 库,该库可在 Arduino IDE 中的“库管理器”中进行安装。
阅读全文