WebIoT

ESP8266 NodeMCU + DHT11 gửi MQTT lên broker — node IoT đơn giản nhất

BiLiChip · 10:30:59 3/12/2026 · 0 lượt xem

Bài mẫu node IoT hoàn chỉnh: ESP8266 NodeMCU đọc DHT11, publish MQTT lên broker public — xem dữ liệu từ xa bằng điện thoại.

Pin map

Chân DHT11Nối vào NodeMCU
VCC3V3
DATAD4 (GPIO2)
GNDGND

Code (PubSubClient + DHT)

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHTPIN D4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

const char* SSID = "TenWiFi";
const char* PASS = "matkhau";
const char* BROKER = "broker.hivemq.com";   // broker public free

WiFiClient wcli;
PubSubClient mqtt(wcli);

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  mqtt.setServer(BROKER, 1883);
}

void reconnect() {
  while (!mqtt.connected()) {
    mqtt.connect("bilichip-node-01");   // client id duy nhat
  }
}

void loop() {
  if (!mqtt.connected()) reconnect();
  mqtt.loop();

  static unsigned long t0 = 0;
  if (millis() - t0 > 10000) {
    t0 = millis();
    float t = dht.readTemperature();
    float h = dht.readHumidity();
    if (!isnan(t)) mqtt.publish("bilichip/nhietdo", String(t).c_str());
    if (!isnan(h)) mqtt.publish("bilichip/doam", String(h).c_str());
  }
}

Xem dữ liệu: app MQTT Dash / IoT MQTT Panel trên điện thoại, subscribe topic bilichip/nhietdo và bilichip/doam.

Lưu ý

  • Broker public (hivemq, mosquitto test) không mã hoá + ai cũng đọc được — chỉ dùng để test; production dùng broker riêng hoặc TLS.
  • Client ID phải duy nhất — 2 node trùng ID sẽ đá nhau reconnect liên tục.
  • NodeMCU chân D4 = GPIO2 (strapping pin — để trống/pull-up khi boot; DHT pull-up sẵn nên OK).
  • Không đọc DHT11 nhanh hơn 1s/lần; DHT22 tối thiểu 2s.
  • Đi xa cần offline: kết hợp thẻ SD làm backup buffer, đồng bộ lại khi có mạng.

0 câu trả lời

Đăng nhập để trả lời câu hỏi này.