Build Project

IoT Projects

ESP32 MQTT DHT22 Sensor Publisher

Publish DHT22 readings to a local MQTT broker, subscribe to a sample command, use unique client IDs and diagnose reconnects. Plain TCP demonstration, not TLS.

IntermediateAges 12+90-120 minUnder 25 USDParent Safe
Illustration of an ESP32 MQTT sensor node and optional dashboard; no dashboard flow is supplied
Jump to a section

What You Will Build

A classic ESP32-WROOM sensor node publishes DHT22 temperature and relative humidity every 30 seconds. An MQTT client subscribes to those topics and can request a fresh sample. Prove the broker exchange first; an existing Node-RED or Home Assistant installation can then display the same topics. This page provides the sensor sketch and CLI verification, not a downloadable dashboard flow.

Before You Start

Classic ESP32-WROOM DevKit / ESP32 Dev Module, Arduino-ESP32 3.3.2 review baseline (not latest). DHT22 on GPIO4, 3.3 V supply and DATA pull-up to 3.3 V. Use a documented 3.3 V-compatible sensor/module; verify its pin orientation and existing pull-up using the DHT22 reference. This is not the DHT11 quick build.

A computer or Raspberry Pi runs an already installed/configured Mosquitto 2.x broker on the same trusted LAN. You need its reachable IPv4 address, a permitted listener, username/password and topic permissions. The broker is not hosted by ESP32 Engine. No sensor measurements, compilation or physical hardware testing were performed for this review.

Parts

Wiring

Connect the documented DHT22 VCC to 3V3, GND to GND and DATA to GPIO4. For a bare sensor add 10 kOhm from DATA to 3V3; inspect a breakout’s fitted pull-up before adding another. The existing diagram shows electrical signal relationships, not a universal module connector order.

ESP32 MQTT Sensor Dashboard wiring diagram

Open wiring diagram full size

  1. 1

    Unplug USB and identify VCC, DATA and GND from the actual sensor documentation.

  2. 2

    Connect VCC to 3V3 and GND to GND.

  3. 3

    Connect DATA to GPIO4 and verify its pull-up to 3V3. Leave a bare DHT22 NC pin unconnected.

  4. 4

    Reconnect USB; first verify the matching DHT22 standalone example, then upload this MQTT sketch.

Wiring Reference

SignalESP32 PinDirectionNotes
DHT22 VCC3.3 VPowerMatch this wire to the code constant.
DHT22 DATAGPIO 4Bidirectional data10 kΩ pull-up to 3.3 V
DHT22 GNDGNDGroundMatch this wire to the code constant.

Libraries and Setup

  • Built-in WiFi from Arduino-ESP32 3.3.2; install PubSubClient by Nick O’Leary version 2.8 through Library Manager.
  • Install Adafruit DHT sensor library 1.4.6 and Adafruit Unified Sensor 1.1.15 (dependency) through Library Manager. No JSON or dashboard library is required on the board.
  • Configure Mosquitto before uploading: 2.x without a listener binds to loopback only; that is not reachable from ESP32. A LAN listener also needs explicitly configured authentication. Follow the linked broker documentation and your platform’s service/firewall instructions.

Configure the Example

Set SSID/PASSWORD for your 2.4 GHz WPA2-Personal network and replace BROKER’s four IPv4 octets with the broker computer’s LAN address. Set MQTT_USER/MQTT_PASSWORD to a broker account permitted to publish and subscribe under esp32engine/sensors/room1/. Do not use the ESP32’s address or 127.0.0.1 as the broker. Change room1 consistently across all five topics when adding another room. The MAC-derived client ID distinguishes boards; topics still need deliberate separation.

From an authorized computer with Mosquitto clients, replace the uppercase placeholders and run: mosquitto_sub -h BROKER_IP -p 1883 -u USER -P PASSWORD -t "esp32engine/sensors/room1/#" -v. In another terminal send: mosquitto_pub -h BROKER_IP -p 1883 -u USER -P PASSWORD -t "esp32engine/sensors/room1/cmd" -m sample. Do not set retain on this command. These are local test instructions, not commands executed during review. Command-line passwords can appear in history/process listings; use disposable local test credentials and your client’s supported secure configuration for real deployments.

Control and Recovery Behavior

ConditionResult
Wi-Fi unavailable15-second asynchronous connection window; starts no more often than every 30 seconds. Sensor schedule keeps running.
Broker unavailableOne synchronous connect attempt, then at least 10 seconds of backoff; no endless retry loop.
Broker reconnectsClean-session connection; subscribe to CMD again and publish retained online availability.
sample commandCallback validates the byte span and sets a flag; loop samples when at least 2500 ms has elapsed.
Sensor failsNo new values; previous retained readings remain old. No offline replay buffer.

Code

Install the libraries above and match the configuration and wiring before uploading.

esp32-mqtt-sensor-dashboard.ino
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <cstring>

const char* SSID = "YOUR_WIFI_SSID";
const char* PASSWORD = "YOUR_WIFI_PASSWORD";
IPAddress BROKER(192, 168, 1, 100); // Replace with your broker's LAN IPv4 address.
const char* MQTT_USER = "YOUR_MQTT_USER";
const char* MQTT_PASSWORD = "YOUR_MQTT_PASSWORD";
const char* TEMP = "esp32engine/sensors/room1/temperature";
const char* HUM = "esp32engine/sensors/room1/humidity";
const char* AVAIL = "esp32engine/sensors/room1/availability";
const char* CMD = "esp32engine/sensors/room1/cmd";
const char* REPLY = "esp32engine/sensors/room1/reply";
constexpr uint32_t WIFI_WINDOW = 15000, WIFI_RETRY = 30000, MQTT_RETRY = 10000;
DHT dht(4, DHT22);
WiFiClient net; // Plain TCP. This sketch does NOT provide TLS.
PubSubClient mqtt(net);
String clientId;
bool wifiTrying = false, sampleRequested = false;
uint32_t wifiStarted = 0, mqttAttempt = 0, lastSample = 0;

void onMessage(char* topic, byte* payload, unsigned int length) {
  // Payload is a byte span, not a null-terminated string.
  if (strcmp(topic, CMD) == 0 && length == 6 && memcmp(payload, "sample", 6) == 0)
    sampleRequested = true;
}
void startWiFi() {
  wifiStarted = millis(); wifiTrying = true;
  WiFi.begin(SSID, PASSWORD);
  Serial.println("Starting 15-second Wi-Fi window");
}
void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.mode(WIFI_STA); WiFi.setAutoReconnect(false);
  clientId = String("esp32-") + WiFi.macAddress();
  clientId.replace(":", ""); // Different hardware gets a different client ID.
  Serial.print("MQTT client ID: "); Serial.println(clientId);
  net.setConnectionTimeout(3000); // TCP connection timeout, milliseconds.
  mqtt.setSocketTimeout(3);       // MQTT response/read timeout, seconds.
  mqtt.setServer(BROKER, 1883);
  mqtt.setCallback(onMessage);
  mqttAttempt = millis() - MQTT_RETRY;
  startWiFi();
}
void loop() {
  uint32_t now = millis();
  if (WiFi.status() != WL_CONNECTED) {
    net.stop(); // Drop a stale broker socket; keep the sensor loop active.
    if (wifiTrying && now - wifiStarted >= WIFI_WINDOW) {
      WiFi.disconnect(false); wifiTrying = false;
      Serial.println("Wi-Fi window ended; retry at 30-second cadence");
    }
    if (!wifiTrying && now - wifiStarted >= WIFI_RETRY) startWiFi();
  } else {
    wifiTrying = false;
    if (!mqtt.connected() && now - mqttAttempt >= MQTT_RETRY) {
      Serial.println("Attempting broker connection");
      if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD, AVAIL, 0, true, "offline")) {
        const bool subscribed = mqtt.subscribe(CMD, 0);
        const bool announced = mqtt.publish(AVAIL, "online", true);
        Serial.printf("Connected: subscribe queued=%d, online queued=%d\n", subscribed, announced);
      } else Serial.printf("Broker connect failed: state=%d\n", mqtt.state());
      mqttAttempt = millis(); // Backoff starts AFTER the synchronous call returns.
    }
    if (mqtt.connected()) mqtt.loop();
  }
  now = millis();
  // Never let command bursts violate the DHT22's >2-second sampling interval.
  if (now - lastSample >= 30000 || (sampleRequested && now - lastSample >= 2500)) {
    lastSample = now; sampleRequested = false;
    const float h = dht.readHumidity(), t = dht.readTemperature();
    if (isnan(h) || isnan(t)) Serial.println("DHT22 read failed; no new values published");
    else {
      Serial.printf("Sensor: temp=%.2f C, humidity=%.2f %%\n", t, h);
      if (mqtt.connected()) {
        const bool a = mqtt.publish(TEMP, String(t, 2).c_str(), true);
        const bool b = mqtt.publish(HUM, String(h, 2).c_str(), true);
        const bool c = mqtt.publish(REPLY, "sample read; values attempted", false);
        Serial.printf("QoS 0 publish results: temp=%d, humidity=%d, reply=%d\n", a, b, c);
      } else Serial.println("Offline: reading not buffered for replay");
    }
  }
  delay(10);
}

How the Code Works

PubSubClient 2.8 implements MQTT 3.1.1 by default. Its publish API uses QoS 0; true means the local write was accepted, not an application acknowledgement or guaranteed delivery. subscribe’s return similarly confirms local submission, not that your account received permission. mqtt.loop() processes incoming messages and keepalive; it must run regularly while connected. The payload callback uses its length and never assumes a terminating zero byte.

There are no while-not-connected loops. Wi-Fi attempts have a finite window; broker connect is still a synchronous call that can pause loop for seconds. The TCP connection timeout is 3000 ms and MQTT socket timeout is 3 seconds; these are separate phases, not a hard three-second total-loop guarantee. Use an asynchronous design for strict real-time workloads. After a connection loss, stale TCP is stopped and the client reconnects/resubscribes.

A retained temperature/humidity is the broker’s latest value, not evidence of current sensor health. The retained availability topic becomes online on connection; the broker’s last will announces offline after it detects an unexpected disconnect, not instantly at power loss. A sensor failure while connected does not change that connection-level availability. Subscribers should track age/status separately.

Expected Output

Illustrative expectations only: Serial prints a unique client ID, connection diagnostics and Sensor: temp=... C, humidity=... %. The subscriber should receive retained temperature/humidity and online availability. Send sample without retain; after the 2500 ms minimum sample spacing, a successful read attempts values and a non-retained reply. This reply is an application message, but itself uses QoS 0 and is not proof of delivery. No Node-RED flow is supplied; configure your own MQTT-in node for the exact topics after the CLI exchange works.

Troubleshooting

  • Wi-Fi or broker never connects Use the Wi-Fi diagnostic guide. Check broker LAN IP, listener/interface, firewall and service logs. Mosquitto loopback-only mode cannot accept the board.
  • MQTT state is -2 or -4 -2 is connect failed; -4 is MQTT connection timeout. Check reachable listener and broker response. TCP timeout and MQTT response timeout are different stages.
  • State 4/5 or subscription receives nothing Check broker username/password and topic ACLs. States 4 and 5 indicate credential/authorization refusal at connection. A subscribe return true alone does not prove topic authorization.
  • One device repeatedly disconnects another Ensure distinct client IDs; this sketch derives one from each STA MAC. Also separate room topic namespaces.
  • Old readings look current Retained values persist; inspect availability and last-received age. A failed DHT22 read publishes no replacement.
  • DHT22 returns NAN Use the separate DHT22 wiring/code reference; verify GPIO4, pull-up, voltage and minimum sample spacing. The DHT11 quick build uses a different sensor type.

Checks to Perform on Your Build

  • Verify the standalone DHT22 reading with the actual sensor before adding MQTT.
  • Use the local subscriber to observe all topics; request sample without retain.
  • Stop/restart the broker and check reconnection/resubscription. Interrupt Wi-Fi and confirm sensor Serial output remains scheduled.
  • Check two boards use different client IDs/topics. Observe stale retained values deliberately; do not mistake them for new measurements.

Practical Design Notes

MQTT separates producers from consumers: the broker routes messages by topic, not by a dashboard URL. Unique client IDs prevent one node disconnecting another; client IDs do not authenticate users. PubSubClient supports QoS 0 publishing and QoS 0/1 subscribing, so do not promise QoS 1 publishing from this sketch.

This is plain TCP with WiFiClient on port 1883. TLS requires a suitable secure client, broker TLS listener and certificate/hostname verification; changing a port number alone is not TLS. Broker credentials and topic ACLs remain necessary. The command only requests a sample; it controls no actuator. Protect broader command interfaces separately. DHT22 sampling here is greater than two seconds and separate from the library’s 2000 ms cache.

Upgrade Ideas

  • Connect a configured Node-RED/Home Assistant MQTT subscriber to the proven topics.
  • Add a last-reading timestamp/validity field before using the readings for decisions.
  • Design a TLS connection with certificate verification for networks beyond this trusted bench.

FAQs

Does changing port 1883 to 8883 enable TLS?

No. This sketch uses a plain WiFiClient. A TLS design needs the secure client and a verified broker certificate/hostname plus the broker’s TLS listener.

Are readings saved while offline?

No. Serial can show readings, but the sketch has no replay buffer. Retained broker values remain old until a new publish succeeds.

Can PubSubClient publish with QoS 1?

Its 2.8 publish API uses QoS 0. It can subscribe at QoS 0 or 1; use a different reviewed client/protocol design if you need QoS 1 publishing.

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-11-03. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.

Educational level: Intermediate. Estimated completion time: 90-120 min. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.