📡 ESP32 MQTT 实战:温湿度数据上云

📅 2026.05.22 · ESP32 实战
🎯 器材:ESP32 + DHT22 · AI Know 物联网系列
📖 项目简介

上节课我们用 ESP32 连上了 WiFi,但 HTTP 请求每次都要建立连接,不适合频繁上报数据。MQTT 是物联网领域最流行的轻量级消息协议,一条连接就能双向通信。今天我们把 DHT22 温湿度数据通过 MQTT 发送到公共 Broker,实现数据上云。

学习目标:理解 MQTT 发布/订阅模型;用 PubSubClient 库连接 MQTT Broker;定时推送传感器数据到云端。

📺 B站推荐视频:ESP32 入门教程

🔌 所需元器件
器件数量备注
ESP32 开发板1任意型号
DHT22 温湿度模块1或 DHT11
杜邦线3 条母对母
10kΩ 电阻1部分模块已内置
🔌 接线: DHT22 VCC → ESP32 3.3V,DATA → GPIO4,GND → GND。DATA 与 VCC 之间接 10kΩ 上拉电阻。
💻 完整代码
// 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);
  }
}
📟 串口输出示例
🔄 连接 WiFi...
✅ WiFi 已连接, IP: 192.168.1.100
🔄 连接 MQTT...
✅ 已连接
📤 发布 {"temp":26.3,"hum":58.2} → esp32/dht22/data
📤 发布 {"temp":26.4,"hum":58.0} → esp32/dht22/data
🛠 验证方法

在电脑上安装 MQTTX(免费客户端),连接到 broker.emqx.io:1883,订阅主题 esp32/dht22/data,就能看到 ESP32 实时推送的数据了。

💡 提示: 也可以用手机 App "MQTT Dashboard" 订阅主题,在手机上实时查看温湿度数据。
🔍 常见问题
🚀 拓展进阶

掌握基础 MQTT 后,你可以: