NodeMCU + MQTT + Multi DHT sensors

Hello to all,
I am continuing my experience with openhab trying to create components that can be added to my current configuration.
My intent now is to read the temperture and, why not, the humidity in every room of the house.
To this end, I searched the net, but I did not find exactly what I am looking for, therefore, as a novice as I am, I made a jumble of the information collected on the web.
I have arduino uno, but I also found a NodeMCU V2 card that I bought some time ago.
Now I purchased 5 DHT22 and am waiting for them to arrive.
In the meantime, I am trying to write an arduino schetch so that I can read all the sensors with a single board and transmit the data to openhab via the MQTT protocol.
I’ll post my schetch, if anyone has comments and / or suggestions, they will be welcome, I’m eager to try it.
If what I’m looking for already exists, please accept my apologies and kindly if you can give me a link.

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

#define wifi_ssid "xxx" //enter your WIFI SSID
#define wifi_password "xxx" //enter your WIFI Password

#define mqtt_server "xxx" // Enter your MQTT server address or IP
#define mqtt_device "xxx" //Enter MQTT device for broker name
#define mqtt_user "xxx" //enter your MQTT username
#define mqtt_password "xxx" //enter your MQTT password

#define humidity_topic "sensor/humidity" //MQTT Topics (change as you wish)
#define temperature_topic "sensor/temperature" //MQTT Topics (change as you wish)

#define NumOfSensor 4 // define how many sensors use

#define DHTPIN1 1 // define digital pin connection of sensor "x"
#define DHTPIN2 2 // define digital pin connection of sensor "x"
#define DHTPIN3 3 // define digital pin connection of sensor "x"
#define DHTPIN4 4 // define digital pin connection of sensor "x"
// #define DHTPINX X (continue if you have more sensors connected or comment previous if you have less)

WiFiClient espClient;
PubSubClient client(espClient);

// create array of sensors DHT22, you can change DHT22 with DHT11 if you need
DHT dht[] = {
  {DHTPIN1, DHT22},
  {DHTPIN2, DHT22},
  {DHTPIN3, DHT22},
  {DHTPIN4, DHT22}, //continue if you have more sensors connected or comment previous if you have less

float h[NumOfSensor]; //create float array for the humidity
float t[NumOfSensor]; //create float array for the temperature
float lastH[NumOfSensor]; //create float array for historical humidity
float lastT[NumOfSensor]; //create float array for historical temperature

String sensor[NumOfSensor]; //create string array called sensor

long lastMsg = 0;

void setup() {

 // Initialize the sensors
  for (auto& sensor : dht) {  
  client.setServer(mqtt_server, 1883); //change port if needed

void loop() {
  if (!client.connected()) {
  // Wait a few seconds between measurements.
  long now = millis();
  if (now - lastMsg > 30000) {
    lastMsg = now;

    for (int i = 0; i < NumOfSensor; i++) { //read values from all sensors
     t[i] = dht[i].readTemperature();
     h[i] = dht[i].readHumidity();

   // Check if any reads failed and exit early (to try again).
    for (int i = 0; i < NumOfSensor; i++) {
      if (isnan(t[i]) || isnan(h[i])) {
        sensor[i] = i;
        Serial.print("Failed to read from DHT sensor:");
        t[i] = lastT[i]; //write previous temperature if attempt temperature failed
        h[i] = lastH[i]; //write previous humidity if attempt humidity failed
      else {
        lastT[i] = t[i]; //store values temperatire if next read fails
        lastH[i] = h[i]; //store values humidity if next read fails
  for (int i = 0; i < NumOfSensor; i++) {
      Serial.print(F("New temperature:"));
      client.publish(temperature_topic, String(t[i]).c_str(), true);

      Serial.print(F("New humidity:"));
      client.publish(humidity_topic, String(h[i]).c_str(), true);

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

  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {

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

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
    } else {
      Serial.print("failed, rc=");
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying


The DHT22 has a max cable lenght of 1m if using 3.3v.

If you want to have one in each room you can use tasmota to publish the data to you mqtt server just make sure you flash one compiled to use sensors tasmota-sensors.bin

Another option is EspEasy firmware. I use both with several esp devices so you may want to give each a try and see what you like.

1 Like

TnX for your answer.
Now I’m away from home, so I can’t try, but I’ve already had some problems before leaving home.
I have a Macbook pro with only the USB-C port and I have not been able to connect NodeMCU to the Arduino IDE.
I installed the drivers of silicon Labs, but no luck.
Do you have any indications to give me about it?
What did you think of ESP-HOME?


That’s not an OH problem but I will give you some advice anyway. :grin: Try using Atom (a text editor) that will work as an IDE for ESP and Arduino. IMHO it’s much easier to connect and work with than Arduino IDE. Check YouTube as there are several videos that will walk you thru the how to.

Never looked into it, but will have a look if I get time.

Looks like it’s for Home Assistant and I didn’t see a GUI interface for the actual device it may work with OH, not sure. With all the options you can try as many as you like and decided what you like best. :wink:

I had to download the CH341SER Driver to be able to flash NodeMCU with MAC.
I installed the Tasmota FW at the moment, but I can only read 4 DHT sensor, do you know if modifing the line: “#define DHT_MAX_SENSORS 4” in “5” is possible to read 5 sensors? Or do I have modify something else?
Is EspEasy able to read more DHT sensors?


You can give it a try and see if it works, worst case you have to change back to 4. For Tasmota related questions check github or the tasmota forum.

Not sure as I do not have 5 sensors connected to a single device but same as Tasmota give it a try or check their site.

Also if testing with different firmware I found that it’s best to completly erase the chip before flashing a new firmware. For this I use esptool and this command: erase_flash

I’m tinkering with a “NodeMCU lolin V3 ESP8266” and a “Wemos D1 Mini” which I flashed with “ESP Easy Mega” and I have to say that this was indeed easy. Sometime I had 3 Sensors installed to 1 ESP.

I got a problem when installed a fourth (PIR Sensor). But maybe this also can be a problem of less power as I used a USB-Connection from my PC and I didn’t test it with an external power adapter. I think normally one can attach as much sensors as there a free gpio’s. But if this make sense as there are limitations in cable length?.

There’s no need to write sketches. Just connect the ESP to your PC and flash the firmware and postload your WiFi settings and you will see your board in your router.

Enter IP-Address in your browser and you will see the Web-UI of your ESP were you can make your settings for MQTT, sensors, etc.

If I understand the UI correct you can use up to 12 sensors, if enough GPIO’s are available

and if there’s enough Power from the transformer.
One DHT11/DHT22 needs one GPIO

BTW: My sensors (DHT22/DHT11/BME280/HC-SR501) are powerd by 5.0 VIN.

Hi all,
I installed ESP-EASY MEGA on my board, the only way I found to do it is through ATOM “platformio”, when I compile it tells me “2 Success”, but when I go to flash, it initially tells me “success”, but then per second I get a failed.
I can still enter the WEB-UI, but I do not have the opportunity to configure the DHT sensor, as shown in the attached photo.
Through the flashar in windows he just can’t program the board.


P.S. resolved the problem of the device.
Now I have to check the max lenght cable, but I have to change the power supply.
TnX for the moment


1 Like

Hi Franceso,

there’s no need to compile and flash with I’m just using the “ESP.Easy.Flasher.exe”
You don’t have to install it. You can just open by double click.
I think you’re missing some .bin files. The one you need to flash an ESP8266 4MB is attached (552.4 KB)
Just download it and copy it in your .bin - folder.(Zip has a postfix of “txt” as “zip” is not uploadable normally :wink:)

Then plug in your NodeMCU to an USB-Port of your PC and start ESP.Easy.Flasher.exe by double-click and you will get a screen like this:

After flash ist started it take a minute or two and you should get the info that your ESP is flashed and connected to the WiFi (with address). If not connected, pls. press the “program only” Button.

I’m curios about the ma. cable length.


Nice to see you got the firmware loaded on the esp and the GUI up and running with 5 sensors. :+1:

I guess Esp_Easy has at least one advantage over Tasmota. :grinning:

step by step, small successes to keep morale high.
Now, I’m looking for how to configure the MQTT connection in OH, do you have a guide? I’m looking on the forum, but I only find examples with command lines and not with the interface in PAPER UI.


Here is a good post that should help if you want to do everything via PaperUI, at least the Things part.

BTW: I know it says Tasmota but the steps for creating the thing will be the same.

I looked at 3D and read the documentation regarding the REST API, but it seems more connected to an HTTP connection, but maybe I translate it wrong.
I have already created the THING element and the channel (at the moment one) as I did for the tasmota, but I cannot understand how to collect and send requests / data from the ESPEASY.
Tonight I will attach an image of what I have done.

you just get data as you get it from tasmota, via MQTT. Do you have a MQTT-Sniffer like “MQTT.fx” ? Have a look in there, you can see what your “Test_DHT” is subscribing to the broker

Your channel should look like this:

You don’t need any JSON-Translation.

How are your espeasy-controller-settings for mqtt ? Here is an example of mine:

Standard is “%sysname%”. If your using standard your subscribe will begin with “Test_DHT/Sensore1/Temperatura”.

I did all the same, just I don’t have %s in “outgoing Value Format”.
Now I’m in office, this night I’ll check with MQTT.fx, at the moment I have “Test_DHT/Sensore1/Temperatura” in “MQTT State Topic”, but is not working.
In the ESP EASY Controller I don’t have “ON-OFF” in the last two line “LWT Connect Message …”
And right I have %sysname% in controller Subscribe.


You need to use a leading / for ESP Easy topic like below.


My Things example:

Thing topic Esp1 "Garage Light Level" @ "Garage" {
        Type number : level  "Light Level"          [ stateTopic="/Esp1/Garage/LightLevel" ]
        Type switch : contact  "Open Closed"        [ stateTopic="/Esp1/Door/Switch", transformationPattern="" ]
        Type switch : motion  "Motion"              [ stateTopic="/Esp1/Motion/Switch", transformationPattern="" ]

You need to use a leading / for ESP Easy topic like below.

Don’t think this is necessary, i.e. I’m using ESPEasy and don’t use leading /.

That said, not sure which version of ESPEasy you use, but there is an issue in latest code that appends space chars to the topic, if host name is less than 9 chars. Please see here. Easy workaround is to use hostname with more than 8 chars, i.e. Test_DHT_X.

Spend quite some time debugging this since i.e. in MQTT.fx its hard to see space at the end of the topic. Please switch to log view where topic is printed with ` so you can see exactly what chars it consists from.

I changed the name in Test_DHT_1
I include the image with all sensor working.
Tomorrow I’ll check with a long cable and a 5Vdc supply if still work.
1 more question, wich is the tag to see the temperature and Humidity in Google home/app? Is possible that I can see the temperature only in a homekit mode?


Chanel Image:

item file:

Number TSensore1 "TemperaturaS1 [%.1f °C]" (gTest-DHT) [ "CurrentTemperature" ]
Number USensore1 "UmiditaS1 [%.1f %%]" (gTest-DHT) [ "CurrentHumidity" ]
Number TSensore2 "TemperaturaS2 [%.1f °C]" (gTest-DHT) [ "CurrentTemperature" ]
Number USensore2 "UmiditaS2 [%.1f %%]" (gTest-DHT) [ "CurrentHumidity" ]
Number TSensore3 "TemperaturaS3 [%.1f °C]" (gTest-DHT) [ "CurrentTemperature" ]
Number USensore3 "UmiditaS3 [%.1f %%]" (gTest-DHT) [ "CurrentHumidity" ]
Number TSensore4 "TemperaturaS4 [%.1f °C]" (gTest-DHT) [ "CurrentTemperature" ]
Number USensore4 "UmiditaS4 [%.1f %%]" (gTest-DHT) [ "CurrentHumidity" ]
Number TSensore5 "TemperaturaS5 [%.1f °C]" (gTest-DHT) [ "CurrentTemperature" ]
Number USensore5 "UmiditaS5 [%.1f %%]" (gTest-DHT) [ "CurrentHumidity" ]