Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. Troubleshooting
  3. DHT22 verify issue.

DHT22 verify issue.

Scheduled Pinned Locked Moved Troubleshooting
12 Posts 3 Posters 5.2k Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • BrydenB Offline
    BrydenB Offline
    Bryden
    wrote on last edited by Bryden
    #3

    I have the DHT sensor library installed under recommended libraries and can run the DHTtester code no problems.
    I have uploaded the sketch to my nodemcu and its working fine and can see the results via serial monitor

    as shown here

    #include <DHT.h>
    #include <DHT_U.h>
    
    // Example testing sketch for various DHT humidity/temperature sensors
    // Written by ladyada, public domain
    
    #include "DHT.h"
    
    #define DHTPIN 2     // what digital pin we're connected to
    
    // Uncomment whatever type you're using!
    //#define DHTTYPE DHT11   // DHT 11
    #define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)
    
    // Connect pin 1 (on the left) of the sensor to +5V
    // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
    // to 3.3V instead of 5V!
    // Connect pin 2 of the sensor to whatever your DHTPIN is
    // Connect pin 4 (on the right) of the sensor to GROUND
    // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
    
    // Initialize DHT sensor.
    // Note that older versions of this library took an optional third parameter to
    // tweak the timings for faster processors.  This parameter is no longer needed
    // as the current DHT reading algorithm adjusts itself to work on faster procs.
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(9600);
      Serial.println("DHTxx test!");
    
      dht.begin();
    }
    
    void 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");
    }
    

    Ill have a read through your recommended threads to see what else I can troubleshoot.
    I also tried looking at others projects and examples but didn't see much code

    1 Reply Last reply
    0
    • BrydenB Offline
      BrydenB Offline
      Bryden
      wrote on last edited by
      #4

      seems to be fixed after I deleted and reinstalled the DHT library several time.

      Thanks mfalkvidd

      1 Reply Last reply
      1
      • BrydenB Offline
        BrydenB Offline
        Bryden
        wrote on last edited by Bryden
        #5

        Ok so I got it all working, somewhat.

        Im running a NodeMCU with wifi to MQTT with the below sketch. (note removed the header of the code to protect private info, I have had the MQTT/ESP part working fine with other sensors/actuators)

        
        
        #include <ESP8266WiFi.h>
        #include <MySensors.h>
        
        // DHT22
        #include <DHT.h>
        
        // Set this to the pin you connected the DHT's data pin to
        #define DHT_DATA_PIN 4
        
        // Set this offset if the sensor has a permanent small offset to the real temperatures
        #define SENSOR_TEMP_OFFSET 0
        
        // Sleep time between sensor updates (in milliseconds)
        // Must be >1000ms for DHT22 and >2000ms for DHT11
        static const uint64_t UPDATE_INTERVAL = 60000;
        
        // Force sending an update of the temperature after n sensor reads, so a controller showing the
        // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
        // the value didn't change since;
        // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
        static const uint8_t FORCE_UPDATE_N_READS = 10;
        
        #define CHILD_ID_HUM 0
        #define CHILD_ID_TEMP 1
        
        float lastTemp;
        float lastHum;
        uint8_t nNoUpdatesTemp;
        uint8_t nNoUpdatesHum;
        bool metric = true;
        
        MyMessage msgHum(CHILD_ID_HUM, V_HUM);
        MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
        DHT dht;
        
        
        void presentation()  
        { 
          // Send the sketch version information to the gateway
          sendSketchInfo("TemperatureAndHumidity", "1.1");
          
          // Register all sensors to gw (they will be created as child devices)
          present(CHILD_ID_HUM, S_HUM);
          present(CHILD_ID_TEMP, S_TEMP);
          
          metric = getControllerConfig().isMetric;
        }
        
        void setup()
        {
          dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
          if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
            Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
          }
          // Sleep for the time of the minimum sampling period to give the sensor time to power up
          // (otherwise, timeout errors might occure for the first reading)
          sleep(dht.getMinimumSamplingPeriod());
        }
        
        
        void loop()      
        {  
          // Force reading sensor, so it works also after sleep()
          dht.readSensor(true);
          
          // Get temperature from DHT library
          float temperature = dht.getTemperature();
          if (isnan(temperature)) {
            Serial.println("Failed reading temperature from DHT!");
          } else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
            // Only send temperature if it changed since the last measurement or if we didn't send an update for n times
            lastTemp = temperature;
            if (!metric) {
              temperature = dht.toFahrenheit(temperature);
            }
            // Reset no updates counter
            nNoUpdatesTemp = 0;
            temperature += SENSOR_TEMP_OFFSET;
            send(msgTemp.set(temperature, 1));
        
            #ifdef MY_DEBUG
            Serial.print("T: ");
            Serial.println(temperature);
            #endif
          } else {
            // Increase no update counter if the temperature stayed the same
            nNoUpdatesTemp++;
          }
        
          // Get humidity from DHT library
          float humidity = dht.getHumidity();
          if (isnan(humidity)) {
            Serial.println("Failed reading humidity from DHT");
          } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
            // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
            lastHum = humidity;
            // Reset no updates counter
            nNoUpdatesHum = 0;
            send(msgHum.set(humidity, 1));
            
            #ifdef MY_DEBUG
            Serial.print("H: ");
            Serial.println(humidity);
            #endif
          } else {
            // Increase no update counter if the humidity stayed the same
            nNoUpdatesHum++;
          }
        
          // Sleep for a while to save energy
          sleep(UPDATE_INTERVAL); 
        }
        

        Basically a copy paste of what on the mysensors page, however this code fails reading the DHT22/am2302 sensor Im using.

        If I use the DHT_Test code supplied with the mysensors master library, everything works fine, same pin, not even re powering the device, flashed it many times, and I'm stuck.

        #include "DHT.h"
        
        DHT dht;
        
        void setup()
        {
          Serial.begin(9600);
          Serial.println();
          Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");
        
          dht.setup(2); // data pin 2
        }
        
        void loop()
        {
          delay(dht.getMinimumSamplingPeriod());
        
          float humidity = dht.getHumidity();
          float temperature = dht.getTemperature();
        
          Serial.print(dht.getStatusString());
          Serial.print("\t");
          Serial.print(humidity, 1);
          Serial.print("\t\t");
          Serial.print(temperature, 1);
          Serial.print("\t\t");
          Serial.println(dht.toFahrenheit(temperature), 1);
        }
        
        mfalkviddM 1 Reply Last reply
        0
        • BrydenB Bryden

          Ok so I got it all working, somewhat.

          Im running a NodeMCU with wifi to MQTT with the below sketch. (note removed the header of the code to protect private info, I have had the MQTT/ESP part working fine with other sensors/actuators)

          
          
          #include <ESP8266WiFi.h>
          #include <MySensors.h>
          
          // DHT22
          #include <DHT.h>
          
          // Set this to the pin you connected the DHT's data pin to
          #define DHT_DATA_PIN 4
          
          // Set this offset if the sensor has a permanent small offset to the real temperatures
          #define SENSOR_TEMP_OFFSET 0
          
          // Sleep time between sensor updates (in milliseconds)
          // Must be >1000ms for DHT22 and >2000ms for DHT11
          static const uint64_t UPDATE_INTERVAL = 60000;
          
          // Force sending an update of the temperature after n sensor reads, so a controller showing the
          // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
          // the value didn't change since;
          // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
          static const uint8_t FORCE_UPDATE_N_READS = 10;
          
          #define CHILD_ID_HUM 0
          #define CHILD_ID_TEMP 1
          
          float lastTemp;
          float lastHum;
          uint8_t nNoUpdatesTemp;
          uint8_t nNoUpdatesHum;
          bool metric = true;
          
          MyMessage msgHum(CHILD_ID_HUM, V_HUM);
          MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
          DHT dht;
          
          
          void presentation()  
          { 
            // Send the sketch version information to the gateway
            sendSketchInfo("TemperatureAndHumidity", "1.1");
            
            // Register all sensors to gw (they will be created as child devices)
            present(CHILD_ID_HUM, S_HUM);
            present(CHILD_ID_TEMP, S_TEMP);
            
            metric = getControllerConfig().isMetric;
          }
          
          void setup()
          {
            dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
            if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
              Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
            }
            // Sleep for the time of the minimum sampling period to give the sensor time to power up
            // (otherwise, timeout errors might occure for the first reading)
            sleep(dht.getMinimumSamplingPeriod());
          }
          
          
          void loop()      
          {  
            // Force reading sensor, so it works also after sleep()
            dht.readSensor(true);
            
            // Get temperature from DHT library
            float temperature = dht.getTemperature();
            if (isnan(temperature)) {
              Serial.println("Failed reading temperature from DHT!");
            } else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
              // Only send temperature if it changed since the last measurement or if we didn't send an update for n times
              lastTemp = temperature;
              if (!metric) {
                temperature = dht.toFahrenheit(temperature);
              }
              // Reset no updates counter
              nNoUpdatesTemp = 0;
              temperature += SENSOR_TEMP_OFFSET;
              send(msgTemp.set(temperature, 1));
          
              #ifdef MY_DEBUG
              Serial.print("T: ");
              Serial.println(temperature);
              #endif
            } else {
              // Increase no update counter if the temperature stayed the same
              nNoUpdatesTemp++;
            }
          
            // Get humidity from DHT library
            float humidity = dht.getHumidity();
            if (isnan(humidity)) {
              Serial.println("Failed reading humidity from DHT");
            } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
              // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
              lastHum = humidity;
              // Reset no updates counter
              nNoUpdatesHum = 0;
              send(msgHum.set(humidity, 1));
              
              #ifdef MY_DEBUG
              Serial.print("H: ");
              Serial.println(humidity);
              #endif
            } else {
              // Increase no update counter if the humidity stayed the same
              nNoUpdatesHum++;
            }
          
            // Sleep for a while to save energy
            sleep(UPDATE_INTERVAL); 
          }
          

          Basically a copy paste of what on the mysensors page, however this code fails reading the DHT22/am2302 sensor Im using.

          If I use the DHT_Test code supplied with the mysensors master library, everything works fine, same pin, not even re powering the device, flashed it many times, and I'm stuck.

          #include "DHT.h"
          
          DHT dht;
          
          void setup()
          {
            Serial.begin(9600);
            Serial.println();
            Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");
          
            dht.setup(2); // data pin 2
          }
          
          void loop()
          {
            delay(dht.getMinimumSamplingPeriod());
          
            float humidity = dht.getHumidity();
            float temperature = dht.getTemperature();
          
            Serial.print(dht.getStatusString());
            Serial.print("\t");
            Serial.print(humidity, 1);
            Serial.print("\t\t");
            Serial.print(temperature, 1);
            Serial.print("\t\t");
            Serial.println(dht.toFahrenheit(temperature), 1);
          }
          
          mfalkviddM Offline
          mfalkviddM Offline
          mfalkvidd
          Mod
          wrote on last edited by
          #6

          @Bryden when the reading fails, what is the result? No reading at all? Incorrect temperature?

          1 Reply Last reply
          0
          • BrydenB Offline
            BrydenB Offline
            Bryden
            wrote on last edited by
            #7

            Its serial printing "Failed reading temperature from DHT" and "Failed reading humidity from DHT" as per the void loop in the sketch.

            I can run DHT_Test, and it works fine, serial printing OK 1.0 25.8 47.3 (or what ever the temp and humidity is) then immediately upload the mysensor sketch and get the failed reading returns.

            AWIA 1 Reply Last reply
            0
            • BrydenB Bryden

              Its serial printing "Failed reading temperature from DHT" and "Failed reading humidity from DHT" as per the void loop in the sketch.

              I can run DHT_Test, and it works fine, serial printing OK 1.0 25.8 47.3 (or what ever the temp and humidity is) then immediately upload the mysensor sketch and get the failed reading returns.

              AWIA Offline
              AWIA Offline
              AWI
              Hero Member
              wrote on last edited by
              #8

              @Bryden try to replace sleep() with wait(). I cannot get sleep to work well on an esp8266.

              BrydenB 1 Reply Last reply
              1
              • AWIA AWI

                @Bryden try to replace sleep() with wait(). I cannot get sleep to work well on an esp8266.

                BrydenB Offline
                BrydenB Offline
                Bryden
                wrote on last edited by
                #9

                @AWI said in DHT22 verify issue.:

                @Bryden try to replace sleep() with wait(). I cannot get sleep to work well on an esp8266.

                Well @AWI thats just weird, Its working now, I'm not much of a programmer, But something as little as changing a sleep command to wait fixed the issue is weird as hell.

                Have you got any explanation or should I just blame the angry pixies getting in a huff.

                You have well earned your hero member status.

                mfalkviddM 1 Reply Last reply
                0
                • BrydenB Bryden

                  @AWI said in DHT22 verify issue.:

                  @Bryden try to replace sleep() with wait(). I cannot get sleep to work well on an esp8266.

                  Well @AWI thats just weird, Its working now, I'm not much of a programmer, But something as little as changing a sleep command to wait fixed the issue is weird as hell.

                  Have you got any explanation or should I just blame the angry pixies getting in a huff.

                  You have well earned your hero member status.

                  mfalkviddM Offline
                  mfalkviddM Offline
                  mfalkvidd
                  Mod
                  wrote on last edited by mfalkvidd
                  #10

                  @Bryden on ESP8266, the MySensors sleep function always returns immediately. That causes the code to try to read data from the sensor too soon.

                  From what I understand, the reason that sleep doesn't sleep on ESP8266 is that the ESP8266 requires a full reboot when it wakes up from sleep, which usually isn't what people want when calling sleep.

                  But people don't want immediate return either. I don't know what reasoning was behind designing the MySensors sleep function on ESP8266 but i assume there was a compelling reason to let sleep() return immediately.

                  Maybe a more logical choice would be to let sleep() on ESP8266 do what wait() does?

                  1 Reply Last reply
                  2
                  • BrydenB Offline
                    BrydenB Offline
                    Bryden
                    wrote on last edited by
                    #11

                    I suppose I could remove the sleep / wait function all together seems as it's going to run off mains and not a battery, which is what I would assume people wanted a sleep function for altogether.

                    AWIA 1 Reply Last reply
                    0
                    • BrydenB Bryden

                      I suppose I could remove the sleep / wait function all together seems as it's going to run off mains and not a battery, which is what I would assume people wanted a sleep function for altogether.

                      AWIA Offline
                      AWIA Offline
                      AWI
                      Hero Member
                      wrote on last edited by
                      #12

                      @Bryden The wait() function is a MySensors replacement of the standard delay() in c++. The "added value" here is that wait() lets you listen to incoming messages while doing nothing. Unless you want some activity during waiting for a next reading (like blinking a led or so) I think wait() is rather usefull ;-)

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      13

                      Online

                      11.7k

                      Users

                      11.2k

                      Topics

                      113.1k

                      Posts


                      Copyright 2025 TBD   |   Forum Guidelines   |   Privacy Policy   |   Terms of Service
                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • MySensors
                      • OpenHardware.io
                      • Categories
                      • Recent
                      • Tags
                      • Popular