上节课我们用 ESP32 连上了 WiFi,但 HTTP 请求每次都要建立连接,不适合频繁上报数据。MQTT 是物联网领域最流行的轻量级消息协议,一条连接就能双向通信。今天我们把 DHT22 温湿度数据通过 MQTT 发送到公共 Broker,实现数据上云。
学习目标:理解 MQTT 发布/订阅模型;用 PubSubClient 库连接 MQTT Broker;定时推送传感器数据到云端。
| 器件 | 数量 | 备注 |
|---|---|---|
| ESP32 开发板 | 1 | 任意型号 |
| DHT22 温湿度模块 | 1 | 或 DHT11 |
| 杜邦线 | 3 条 | 母对母 |
| 10kΩ 电阻 | 1 | 部分模块已内置 |
// mqtt_dht22.ino — 温湿度数据 MQTT 上云 #include <WiFi.h> #include <PubSubClient.h> #include <DHT.h> // WiFi 配置 const char* ssid = "YourWiFi"; const char* password = "YourPassword"; // MQTT 配置(使用公共测试 Broker) const char* mqtt_server = "broker.emqx.io"; const int mqtt_port = 1883; const char* mqtt_topic = "esp32/dht22/data"; // DHT22 配置 #define DHTPIN 4 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); WiFiClient espClient; PubSubClient client(espClient); unsigned long lastMsg = 0; void setup_wifi() { Serial.print("🔄 连接 WiFi"); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\n✅ WiFi 已连接, IP: " + WiFi.localIP().toString()); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("📩 收到消息 ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) Serial.print((char)payload[i]); Serial.println(); } void reconnect() { while (!client.connected()) { Serial.print("🔄 连接 MQTT..."); if (client.connect("ESP32Client")) { Serial.println("✅ 已连接"); client.subscribe("esp32/dht22/cmd"); } else { Serial.print("❌ 失败 rc="); Serial.print(client.state()); delay(5000); } } } void setup() { Serial.begin(115200); dht.begin(); setup_wifi(); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); } void loop() { if (!client.connected()) reconnect(); client.loop(); unsigned long now = millis(); if (now - lastMsg > 10000) { // 每 10 秒上报一次 lastMsg = now; float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println("❌ 传感器读取失败"); return; } // 构建 JSON 数据 char msg[100]; snprintf(msg, 100, "{\"temp\":%.1f,\"hum\":%.1f}", t, h); Serial.printf("📤 发布 %s → %s\n", msg, mqtt_topic); client.publish(mqtt_topic, msg); } }
在电脑上安装 MQTTX(免费客户端),连接到 broker.emqx.io:1883,订阅主题 esp32/dht22/data,就能看到 ESP32 实时推送的数据了。
掌握基础 MQTT 后,你可以: