emqx esp32
时间: 2025-05-02 21:45:44 浏览: 20
### 如何在ESP32上使用EMQX进行MQTT通信
要在ESP32上使用EMQX作为MQTT服务器实现通信,可以按照以下方法完成配置和编程:
#### 1. 配置EMQX MQTT服务器
首先需要设置一个可用的EMQX MQTT服务器。可以选择部署本地服务器或者使用云端服务。
- **本地服务器**:可以通过安装EMQX软件包来搭建本地MQTT服务器[^2]。完成后,在浏览器中访问`http://localhost:18083`进入管理界面。
- **云服务**:也可以注册并使用EMQX Cloud提供的托管服务[^3],这通常更简单快捷。
#### 2. 安装必要的库文件
为了使ESP32能够支持MQTT协议,需在其项目中引入相应的Arduino库。推荐使用的库是PubSubClient,它提供了简单的API用于发布和订阅消息。
```bash
# 在Arduino IDE中打开“工具”->“库管理”,搜索并安装以下库:
# PubSubClient 和 WiFi (如果尚未安装的话)
```
#### 3. 编写ESP32代码示例
下面是一个基本的例子展示如何利用上述提到的库让ESP32连接至EMQX broker,并执行消息的订阅与接收操作。
```cpp
#include <WiFi.h>
#include <PubSubClient.h>
// 替换为实际Wi-Fi名称和密码
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// EMQX Broker地址, 如果是本地则填写IP; 若为远程可填域名
const char* mqtt_server = "broker.emqx.io";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client")) { // 设备ID应唯一
Serial.println("connected");
// Once connected, subscribe to our test topic
client.subscribe("/test/topic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883); // 默认端口号为1883
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// 发布一条测试消息到指定主题
static unsigned long lastMsg = 0;
const unsigned long interval = 10 * 1000;
if (millis() - lastMsg > interval) {
lastMsg = millis();
String message = "Hello from ESP32!";
client.publish("/test/topic", message.c_str());
}
}
```
此程序实现了如下功能:
- 建立Wi-Fi连接;
- 尝试建立与MQTT代理器之间的TCP/IP链接;
- 成功后即刻订阅特定的主题 `/test/topic`;
- 持续监听来自该主题的消息并通过串口打印出来;
- 同时每隔十秒向同一主题广播一次问候语句 “Hello from ESP32!”.
以上过程均依赖于所定义的帮助函数 `setup_wifi`, `callback`, `reconnect`.
#### 4. 测试通信效果
当一切准备就绪之后,上传这段脚本至您的ESP32板子上去运行吧!接着你可以借助其他任何兼容标准MQTT协议的应用程序比如MQTT.fx 或者官方建议的新一代替代品 MQTT X 来验证整个系统的运作状况[^5].
一旦启动成功,你应该能够在终端窗口观察到来自不同方向的数据流交换情况——既包括由外部源推送过来的通知事件,也有出自内部主动发起的信息传递动作。
---
阅读全文
相关推荐

















