How to Publish DHT11 Sensor Data from NodeMCU to Mosquitto MQTT Broker

Introduction:

The Internet of Things (IoT) has become an integral part of our lives, with billions of devices connected to the internet. In the world of IoT, data is the king, and sensors are the eyes and ears. In this blog post, we will discuss how to publish DHT11 sensor data from NodeMCU to Mosquitto MQTT broker.

Setting up the Environment:

Before we start, we need to set up the environment. We will need the following components:

  • NodeMCU board
  • DHT11 Temperature and Humidity Sensor
  • Arduino IDE
  • MQTT Library for Arduino

Connecting DHT11 to NodeMCU:

To connect DHT11 to NodeMCU, we need to connect the following pins:

  • VCC of DHT11 to 3.3V of NodeMCU
  • GND of DHT11 to GND of NodeMCU
  • Data pin of DHT11 to any GPIO pin of NodeMCU. In this example, we will connect it to D2 pin of NodeMCU.

Writing the Code:

After setting up the environment and connecting the DHT11 sensor, we need to write the code to read the data from the sensor and publish it to the MQTT broker. We will use the Adafruit MQTT library for Arduino to publish the data. Here’s the code:

				
					#ifdef ESP8266
  #include <ESP8266WiFi.h>     /* WiFi library for ESP8266 */
#else
  #include <WiFi.h>            /* WiFi library for ESP32 */
#endif
#include <Wire.h>
#include <PubSubClient.h>
#include "DHT.h"             /* DHT11 sensor library */

#define DHTPIN 2
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);

#define wifi_ssid "Fusion Automate"
#define wifi_password "Fusion_Automate"
#define mqtt_server "192.168.1.7"

#define humidity_topic "sensor/DHT11/humidity"
#define temperature_celsius_topic "sensor/DHT11/temperature_celsius"
#define temperature_fahrenheit_topic "sensor/DHT11/temperature_fahrenheit"

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  // dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
    
  if (client.connect("ESP8266Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}


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

      // Wait a few seconds between measurements.
      delay(2000);
      
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);
      
      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
      }
      
      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");

      Serial.print("Temperature in Celsius:");
      Serial.println(String(t).c_str());
      client.publish(temperature_celsius_topic, String(t).c_str(), true);

      Serial.print("Temperature in Fahrenheit:");
      Serial.println(String(f).c_str());
      client.publish(temperature_fahrenheit_topic, String(f).c_str(), true);

      Serial.print("Humidity:");
      Serial.println(String(h).c_str());
      client.publish(humidity_topic, String(h).c_str(), true);
      
}
				
			

Conclusion:

In this blog post, we discussed how to publish DHT11 sensor data from NodeMCU to Mosquitto MQTT broker. We covered the setup of the environment, connecting the DHT11 sensor to NodeMCU, writing the code, and publishing the data to the MQTT broker. With this knowledge, you can now build your own IoT projects and publish data to the MQTT broker.