ESP32 + DHT11/DHT22 + MQTT | Send Sensor Data to MQTTX & My MQTT App

📌 Blogger Post: ESP32 + DHT11/DHT22 + MQTT | Send Sensor Data to MQTTX & My MQTT App

📢 Introduction



Are you interested in IoT and want to learn how to send real-time temperature & humidity data from an ESP32 to an MQTT broker? In this tutorial, we will integrate an ESP32 with a DHT11/DHT22 sensor and publish data to MQTTX & My MQTT App using Arduino IDE.

By the end of this project, you’ll know how to:
✔️ Connect ESP32 with a DHT sensor
✔️ Set up MQTT communication to send & receive data
✔️ Use Arduino IDE to program the ESP32
✔️ Monitor sensor data on MQTTX & My MQTT App
✔️ Control an LED using MQTT commands

Let’s get started! 🚀


📡 Components Required

Component Quantity
ESP32 Development Board 1
DHT11 or DHT22 Sensor 1
10kΩ Resistor (Pull-up) 1
Breadboard & Jumper Wires As needed
Arduino IDE (Software) Installed
MQTT Broker (test.mosquitto.org) Online

📌 Circuit Diagram & Wiring

DHT Sensor to ESP32 Connection:

DHT Pin ESP32 Pin
VCC 3.3V
GND GND
DATA GPIO4 (D4)
10kΩ Resistor Between VCC & DATA

LED to ESP32 Connection:

LED Pin ESP32 Pin
Positive (+) GPIO2
Negative (-) GND

🔧 Coding the ESP32 in Arduino IDE

1️⃣ Install Required Libraries

Before uploading the code, install these libraries:
🔹 DHT Sensor Library
🔹 Adafruit Unified Sensor Library
🔹 PubSubClient (for MQTT)

Go to Arduino IDE → Sketch → Include Library → Manage Libraries, search for them, and install.

2️⃣ ESP32 MQTT Code with DHT Sensor

Upload this code to your ESP32:

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

// WiFi and MQTT Broker Details
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];

// Define Pins
#define LED_PIN 2
#define DHTPIN 4
#define DHTTYPE DHT11 // Change to DHT22 if using it

DHT dht(DHTPIN, DHTTYPE);

void setup_wifi() {
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected. IP Address: " + WiFi.localIP().toString());
}

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();

  if ((char)payload[0] == '1') {
    digitalWrite(LED_PIN, LOW);
  } else {
    digitalWrite(LED_PIN, HIGH);
  }
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(esp_random(), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.publish("device/status", "ESP32 Connected");
      client.subscribe("device/led");
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println(" Retrying in 5 seconds...");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  Serial.begin(115200);
  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();

    if (isnan(temperature) || isnan(humidity)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    snprintf(msg, MSG_BUFFER_SIZE, "Temp: %.2f°C, Humidity: %.2f%%", temperature, humidity);
    Serial.print("Publishing message: ");
    Serial.println(msg);

    client.publish("device/temp", String(temperature).c_str());
    client.publish("device/humidity", String(humidity).c_str());
  }
}

📡 Testing with MQTTX & My MQTT App

✅ Open MQTTX and connect to test.mosquitto.org
✅ Subscribe to device/temp and device/humidity
✅ Publish "1" to device/led → LED turns ON
✅ Publish "0" to device/led → LED turns OFF


📌 Video Tutorial 🎥

📺 Watch My YouTube Video: ESP32 MQTT with DHT Sensor

🔔 Subscribe for More IoT Projects!


📢 Follow Me on Social Media

📷 Instagram: @roberemon
🐦 Twitter (X): @abs_emon11
💻 GitHub: @ABs-emon
📺 YouTube: @ire-programmer


📌 Conclusion

In this project, we successfully:
✅ Connected an ESP32 with a DHT sensor
✅ Published temperature & humidity data to MQTTX & My MQTT App
✅ Subscribed to MQTT topics to control an LED

🚀 Let me know in the comments if you found this tutorial helpful!

👉 If you liked this project, share it with your friends and subscribe to my channel for more IoT tutorials! 🎯


🔍 Keywords & SEO (For Google Ranking)

📌 Keywords:

ESP32 MQTT, ESP32 DHT11, ESP32 DHT22, ESP32 IoT, ESP32 MQTTX, My MQTT App, ESP32 Temperature Sensor, ESP32 Home Automation, MQTT ESP32 Tutorial, Arduino IDE MQTT, ESP32 Smart Home

📌 Hashtags:
#ESP32 #MQTT #DHT11 #IoT #ArduinoIDE #SmartHome #MyMQTT #MQTTX #ireprogrammer #ESP32Projects

Post a Comment

نموذج الاتصال