DHT22 not being read

Hi,

I have been trying to sort this for a while. I am doing something stupid, I get that but I cannot see what. I can no longer read the DHT22: I am using a WeMos D1 Mini and trying to read a DHT22 for temp and humidity. It all initially worked fine then I replaced my laptop and I guessed I messed up the drivers for the WeMos.

// run on WeMos mini D1
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <ArduinoOTA.h>
#include <BlynkSimpleEsp8266.h>
#include <WidgetRTC.h>
#include "DHT.h"
#include <PID_v1.h>

#define CycleTime 30000 // sensor read and relay process frequency

//define pins
//Wemos board pin location:-
//3V3 D8 D7 D6 D5 D0 A0 DST
//5V G D4 D3 D2 D1 RX TX
#define SystemOnOffRelayPin D0
#define DehumidifierRelayPin D3
#define DHTTempHumiditySensorPin D4
#define Fan2RelayPin D5
#define Fan1RelayPin D6
#define Heater2RelayPin D7
#define Heater1RelayPin D8
#define DHTTYPE DHT11   // DHT 22  (AM2302)

//define Blynk virtual pins
#define vTempSetPoint V0
#define vHeaterActive V1
#define vFanActive V2
#define vDehumActive V3
#define vSystemOnOff V4
#define vEnvironmentalTemp V5
#define vEnvironmentalHumidity V6
#define vTerminal V7
#define vDehumidifierSetPoint V8
#define vSystemStatus V9
#define vVariableStatus V10
#define vSystemActive V11
 
//set up temphumidity sensor
DHT DHTTempHumititySensor(DHTTempHumiditySensorPin, DHTTYPE);

// set up timer function to repeat the sensor read/relay setting/blynk update activities
BlynkTimer DoProcessing; // DoProcessing is the procedure run every time the timer fires - precedure name is variable. see http://playground.arduino.cc/Code/SimpleTimer

// set up the blyn ternila widget to send debuging & status messages to.
WidgetTerminal BlynkConsole (vTerminal);

//WidgetRTC rtc;

// blynk key here
char BlynkAuth[] = "3bcf9c42589a46f6833c74a2a9bf37ee";

// define variables & set defaults
bool isFirstConnect = true;  // Keep this flag not to re-sync on every reconnection
bool bSystemOn = false;
bool bHeaterActive = false;
bool bFanActive = false;
bool bDehumActive = false;
bool bDisplayStatus = false;
bool bDisplayVariable = false;
int iTempSetPoint = 25;
int iHeaterOnTemp = 23;
int iHeaterOffTemp = 27;
int iFanOnTemp = 27;
int iFanOffTemp = 20;
int iDehumidifierSetpoint = 50;
int iReadFailCount = 0;
float EnvironmentTemp;
float EnvironmentHumidity;



// one off initial setups
void setup() {
  Blynk.begin(BlynkAuth,"","");
  Serial.begin(115200);
  delay(10000);
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  wifiManager.setTimeout(180);
  BlynkConsole.println("Firing Up"); // sends message to blynk terminal widget in blynk app on phone
  BlynkConsole.flush();
  Serial.println("connected...yeey :)");
//  wifiManager.resetSettings(); // if want to delete ssid settings
//  wifiManager.startConfigPortal("WeMos 01"); // make it load the portal

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //and goes into a blocking loop awaiting configuration

  if(!wifiManager.autoConnect("Monitor Status")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  } 

    ArduinoOTA.setHostname("Monitor Status"); //invoke to create the access point name & password
    ArduinoOTA.setPassword("arduino");
    
    ArduinoOTA.onStart([]() {
      Serial.println("Start");
    });
    ArduinoOTA.onEnd([]() {
      Serial.println("\nEnd");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
      Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
      Serial.printf("Error[%u]: ", error);
      if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
      else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
      else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
      else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
      else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();
    BlynkConsole.println("Ready");
    BlynkConsole.flush();

//set up temphumidity sensor
    DHTTempHumititySensor.begin();
    DoProcessing.setInterval(CycleTime, ProcessControl);// set up timer
//    rtc.begin(); 

  // set up digital pins
  pinMode(Heater1RelayPin, OUTPUT);// set mode
  digitalWrite(Heater1RelayPin, LOW); // set to Off I think??
  
  pinMode(Heater2RelayPin, OUTPUT);// set mode
  digitalWrite(Heater2RelayPin, LOW); // set to Off I think??
  
  pinMode(Fan1RelayPin, OUTPUT);// set mode
  digitalWrite(Fan1RelayPin, LOW); // set to Off I think??
  
  pinMode(Fan2RelayPin, OUTPUT);// set mode
  digitalWrite(Fan2RelayPin, LOW); // set to Off I think??
  
  pinMode(SystemOnOffRelayPin, OUTPUT);// set mode
  digitalWrite(SystemOnOffRelayPin, LOW); // set to Off I think??

  pinMode(DehumidifierRelayPin, OUTPUT);// set mode
  digitalWrite(DehumidifierRelayPin, HIGH); // set to On I think??
}

// manage blynk virtual pins
BLYNK_CONNECTED() {
  if (isFirstConnect) {
    // Request Blynk server to re-send latest values for all pins when system fires up.
    Blynk.syncAll();
    isFirstConnect = false;
  }
}

//main programme loop
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  DoProcessing.run(); // Initiates SimpleTimer
}


//procedures & functions
void ProcessControl() { // processed by the timer set to frequency of CycleTime

//regardless of System On (V4) button 
readSensor();           // read the sensors

// if the virtual System On (V4) button is high then do the processes
if(bSystemOn){
  SensorFailure();            // if the sensor fails sets defaults
  systemStatus();             // displays the system status & settings if virtual buttons active (V9 & V10)
  controlHeatersAndFans();    // controls the heaters & fans based on set points (V0)
  controlDehumidifier();      // controls the dehumidifier based on a set point  (V8)
}
else{
  systemOff();                // turns off all the relays and sets flags low
}

// sends all data to Blynk servers
sendDataToBlynk();      
}


void readSensor(){
    EnvironmentHumidity = DHTTempHumititySensor.readHumidity();
    EnvironmentTemp = DHTTempHumititySensor.readTemperature();
  // check if returns are valid, if they are NaN (not a number) then something went wrong!
    if (isnan(EnvironmentTemp) || isnan(EnvironmentHumidity)) {
      Serial.println("Failed to read from Environmental Sensor\n\r");
      BlynkConsole.println("Failed to read from Environmental Sensor\n\r");
      BlynkConsole.flush();
      iReadFailCount ++;
    } 
    else {
      Serial.print("Humidity: "); 
      Serial.print(EnvironmentHumidity);
      Serial.println(" %\t");
      Serial.print("Temperature: "); 
      Serial.print(EnvironmentTemp);
      Serial.println(" ËšC ");
      
      BlynkConsole.print("Humidity: "); 
      BlynkConsole.print(EnvironmentHumidity);
      BlynkConsole.println(" %\t");
      BlynkConsole.print("Temperature: "); 
      BlynkConsole.print(EnvironmentTemp);
      BlynkConsole.println(" ËšC ");           
      BlynkConsole.flush();

      iReadFailCount = 0;
    }  
}

//if the sensor fails to read 10 times define defaults
void SensorFailure(){
  if(iReadFailCount > 9){
    
    //set relays
    digitalWrite(Heater1RelayPin, LOW); // default to Off 
    digitalWrite(Heater2RelayPin, LOW); // default to Off
    digitalWrite(Fan1RelayPin, LOW); // default to Off
    digitalWrite(Fan2RelayPin, LOW); // default to Off
    digitalWrite(SystemOnOffRelayPin, LOW); // default to Off
    digitalWrite(DehumidifierRelayPin, HIGH); // default to On

    //set flags
    bSystemOn = false;
    bHeaterActive = false;
    bFanActive = false;
    bDehumActive = true;

    //prints to console
    BlynkConsole.println("System set to default"); 
    BlynkConsole.flush();
    Serial.println("System set to default");
  }
}

//displays various system status if status variable is selected
void systemStatus(){

//BlynkConsole.print("vSystemStatus: "); 
//BlynkConsole.println(vSystemStatus); 
//BlynkConsole.print("vVariableStatus: "); 
//BlynkConsole.println(vVariableStatus); 
  
  //display values is vSystemStatus (V9) selected 
  if (bDisplayStatus){  
      BlynkConsole.print("System: "); 
      BlynkConsole.println(bSystemOn); 
      BlynkConsole.print("Heater: "); 
      BlynkConsole.println(bHeaterActive); 
      BlynkConsole.print("Fans: "); 
      BlynkConsole.println(bFanActive); 
      BlynkConsole.print("Dehumidifier: "); 
      BlynkConsole.println(bDehumActive); 
      BlynkConsole.flush();
  
      Serial.print("Heater status: ");
      Serial.println(bHeaterActive);   
      Serial.print("Heater status: ");
      Serial.println(bHeaterActive);
      Serial.print("Fan status: ");
      Serial.println(bFanActive);
      Serial.print("Dehum status: ");
      Serial.println(bDehumActive);
  }
  
  //displays variable values is vVariableStatus (V10) selected before checking them 
  if (bDisplayVariable){
     BlynkConsole.print("SetPoint:"); 
     BlynkConsole.println(iTempSetPoint);
     BlynkConsole.print("H_On:"); 
     BlynkConsole.println(iHeaterOnTemp);
     BlynkConsole.print("H_Off:"); 
     BlynkConsole.println(iHeaterOffTemp);
     BlynkConsole.print("F_On:"); 
     BlynkConsole.println(iFanOnTemp);
     BlynkConsole.print("F_Off:"); 
     BlynkConsole.println(iFanOffTemp);
     BlynkConsole.print("D_Off:"); 
     BlynkConsole.println(iDehumidifierSetpoint);
     BlynkConsole.flush();
  
     Serial.print("TempSetPoint: ");
     Serial.println(iTempSetPoint);
     Serial.print("HeaterOnTemp: "); 
     Serial.println(iHeaterOnTemp);
     Serial.print("HeaterOffTemp: ");
     Serial.println(iHeaterOffTemp);
     Serial.print("FanOnTemp: "); 
     Serial.println(iFanOnTemp);   
     Serial.print("FanOffTemp: "); 
     Serial.println(iFanOffTemp); 
     Serial.print("DehumidOff: "); 
     Serial.println(iDehumidifierSetpoint); 
   } 
}
//turns on the heater & fan elements  
void controlHeatersAndFans(){

  // if env temp is <= iHeaterOffTemp variable & the heater flag is low switch Heater_Relay pin(s)"on"
  if (EnvironmentTemp <= iHeaterOffTemp && !bHeaterActive){
      digitalWrite(Heater1RelayPin, HIGH);
  //  digitalWrite(Heater2RelayPin, HIGH);
      bHeaterActive = true;                       // toggle the heater flag
  }

  //if env temp is <= iTempSetPoint variable & the fan flag is high switch Heater2_Relay pin(s)"on"
  //Bring on the second heater if struggling to get to temp
  if (EnvironmentTemp <= iTempSetPoint){
      digitalWrite(Heater2RelayPin, HIGH);
  }

  //turn off the second heater once temp set point is reached
  if (EnvironmentTemp >= iTempSetPoint && bHeaterActive ){
      digitalWrite(Heater2RelayPin, LOW);
  }

  //if the env temp is >= to HeaterOff varibale & the heater flag is high then turn the Heater_Relay pin(s) off
  if (EnvironmentTemp >= iHeaterOffTemp && bHeaterActive ){
      digitalWrite(Heater1RelayPin, LOW);
      digitalWrite(Heater2RelayPin, LOW);
      bHeaterActive = false;                      // toggle the heater flag
  }

  // if env temp >= iFanOnTemp variable and fan is not running switch Fan_Relay pin(s) "on" 
  if (EnvironmentTemp >= iFanOnTemp && !bFanActive){
      digitalWrite(Fan1RelayPin, HIGH);
      digitalWrite(Fan2RelayPin, HIGH);
      bFanActive = true;   
    }
    
  // if env temp <= iFanOffTemp variable and fan is running then switch Fan_Relay pin(s) "Off" 
  if (EnvironmentTemp <= iFanOffTemp && bFanActive){
      digitalWrite(Fan1RelayPin, LOW);
      digitalWrite(Fan2RelayPin, LOW);
      bFanActive = false;
  }
 
}

// function to turn the dehumidifier relay pin "on"(D3)
void controlDehumidifier(){

  // if the enviromental humidity value is < iDehumidifierSetpoint variable then turn the dehumidifier relay pin "off" else default to "on"
  // iDehumidifierSetpoint is a Virtual slider V8, processed BLYNK_WRITE(vDehumidifierSetPoint) 
  if (EnvironmentHumidity <= iDehumidifierSetpoint) {
    digitalWrite(DehumidifierRelayPin, LOW);
    bDehumActive = false;   
    }
  
 if (EnvironmentHumidity >= iDehumidifierSetpoint +1){
        digitalWrite(DehumidifierRelayPin, LOW);
        bDehumActive = true;   
        }
/* else{
   digitalWrite(DehumidifierRelayPin, HIGH);
    bDehumActive = true;
  }*/ 
}

void sendDataToBlynk(){
// V5 Environmental Temp
    Blynk.virtualWrite(vEnvironmentalTemp, EnvironmentTemp);
// V6 Environmental Humidity
    Blynk.virtualWrite(vEnvironmentalHumidity, EnvironmentHumidity);
    
// V1 Heater Active LED
  if(bHeaterActive){
        Blynk.virtualWrite(vHeaterActive,1023);
  }
        else {Blynk.virtualWrite(vHeaterActive,0);
  }
  
// V2 Fan Active LED
  if(bFanActive){
        Blynk.virtualWrite(vFanActive,1023);
  }
        else {Blynk.virtualWrite(vFanActive,0);
  }
  
// V3 Dehumidifier Active LED
  if(bDehumActive){
        Blynk.virtualWrite(vDehumActive,1023);
  }
        else {Blynk.virtualWrite(vDehumActive,0);
  }

  // V11 System Active LED
  if(bSystemOn){
        Blynk.virtualWrite(vSystemActive,1023);
  }
        else {Blynk.virtualWrite(vSystemActive,0);
  }
}

//function to turn off the relays if the virtual System On (V4) button is low (off)
void systemOff(){
//  turn all the relays off
digitalWrite(Heater1RelayPin, LOW); 
digitalWrite(Heater2RelayPin, LOW); 
digitalWrite(Fan1RelayPin, LOW); 
digitalWrite(Fan2RelayPin, LOW); 
digitalWrite(SystemOnOffRelayPin, LOW); 
digitalWrite(DehumidifierRelayPin, LOW); 

// set flags
bHeaterActive = false;
bFanActive = false;
bDehumActive = false;      
}

// V0 Bylink slider widget to set the heater set point
BLYNK_WRITE(vTempSetPoint){ 
   int iSetPoint = param.asInt();

   //setting the enviromental variables
   iTempSetPoint = iSetPoint;
   iHeaterOnTemp = iSetPoint - 2;
   iHeaterOffTemp = iSetPoint + 2;
   iFanOffTemp =  iSetPoint - 5;
   iFanOnTemp =  iSetPoint +1;
}


// V8 Bylink widget for the humidity level
BLYNK_WRITE(vDehumidifierSetPoint) {
 //Humidity level to turn off the dehumidifier 
   int iHumidSetPoint = param.asInt();
   iDehumidifierSetpoint = iHumidSetPoint; 
}


// V4 system on/off button
BLYNK_WRITE(vSystemOnOff) 
{
  bSystemOn = param.asInt();

  if (bSystemOn){
    digitalWrite(SystemOnOffRelayPin, HIGH);
  }
  else
  {
    digitalWrite(SystemOnOffRelayPin, LOW);
  } 
}
// V9 system status on/off button
BLYNK_WRITE(vSystemStatus) 
{
    bDisplayStatus = param.asInt();
    /*//prints to console
    BlynkConsole.print("bDisplayStatus ="); 
    BlynkConsole.println(bDisplayStatus); 
    BlynkConsole.flush();*/

}
// V10 system status on/off button
BLYNK_WRITE(vVariableStatus) 
{
    bDisplayVariable = param.asInt();

    /*BlynkConsole.print("bDisplayVariable ="); 
    BlynkConsole.println(bDisplayVariable); 
    BlynkConsole.flush();*/
}

Can you provide the serial output ?

Hi Coeur

Thanks for your response, sorry I am a bit slow in replying, we had a baby on Thursday! Things are a it hectic.

This is the output from the serial:

11:20:38.561 -> connected…yeey :slight_smile:
11:20:38.561 -> *WM:
11:20:38.561 -> *WM: AutoConnect
11:20:38.594 -> *WM: Connecting as wifi client…
11:20:38.594 -> *WM: Using last saved values, should be faster
11:20:41.797 -> *WM: Connection result:
11:20:41.797 -> *WM: 3
11:20:41.797 -> *WM: IP Address:
11:20:41.797 -> *WM: 192.168.0.14
11:20:41.797 -> *WM: freeing allocated params!
11:21:11.876 -> Failed to read from Environmental Sensor
11:21:11.876 ->

11:21:41.879 -> Failed to read from Environmental Sensor
11:21:41.879 ->

11:22:11.875 -> Failed to read from Environmental Sensor
11:22:11.875 ->

11:22:41.864 -> Failed to read from Environmental Sensor
11:22:41.864 ->

11:23:11.851 -> Failed to read from Environmental Sensor
11:23:11.851 ->

11:23:41.860 -> Failed to read from Environmental Sensor
11:23:41.860 ->

I have checked and I definitely have 5V on the correct pins of the DHT22, I have changed the cables and the hardware (Sensor & WeMos). I have to be doing something stupid in the code but I cannot see it

Pete.

1 Like

Thanks Pete, I have tried using both DHT22 and DHT11 . Current I have defined it as a DHT22 and connected a DHT22 but still get the same error

well seen Pete !

Did you try the DH22 basic example without blynk ?

I think the code is a bit odd anyway, with Blynk.begin (which requires Wi-Fi credentials) before WiFiManager (which allows you to input these credentials). It seems that Blynk.begin is using hard coded credentials, which have been removed, rather than the variables obtained from WiFiManager/SPIFFS.

I think I’d add some Serial.print statements into the readSensor routine to Essex exactly what the Not A Number values are that are coming from the sensor.

I’d also check which DHT library is being uses, incase you have something obscure installed, and as @Blynk_Coeur suggested try a simplified sketch, maybe the Blynk DHT example.

Pete.

1 Like

Thanks Pete, I will try tiding up the code and try again, including some serial.print. The Wifi credentials were bugging me anyway, I had to set up the Wifi first then load this code.

I am using the DHT Sensor library by Adafruit version 1.3.7.

I have tried to use the default code they provide and be unsuccessful there too. Which made me think there was potentially an issue with the library I was using for the WeMos board :ESP8266WiFi.h

I will try the Blynk DHT example

In the Arduino IDE go to File>Preferences and turn on verbose output for compilation.
When it tells you which libraries have been used, is it actually showing the Adafruit library as being the one that is used?

Pete.

Hi Pete

It looks like there is 2 Adafruit libraries. Could that be the issue?

Using library ESP8266WiFi at version 1.0 in folder: C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi
Using library DNSServer at version 1.1.1 in folder: C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\DNSServer
Using library ESP8266WebServer at version 1.0 in folder: C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WebServer
Using library WiFiManager at version 0.15.0-beta in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\WiFiManager
Using library ArduinoOTA at version 1.0 in folder: C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ArduinoOTA
Using library blynk-library-master at version 0.6.1 in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\blynk-library-master
Using library Time-master at version 1.5 in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\Time-master
Using library DHT_sensor_library at version 1.3.7 in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\DHT_sensor_library
Using library Arduino-PID-Library-master at version 1.2.1 in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\Arduino-PID-Library-master
Using library ESP8266mDNS at version 1.2 in folder: C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266mDNS
Using library Adafruit_Unified_Sensor at version 1.0.3 in folder: C:\UserData\phillip.day\Documents\Arduino\libraries\Adafruit_Unified_Sensor
“C:\Users\phillip.day\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-3-20ed2b9/bin/xtensa-lx106-elf-size” -A

No, that’s fine. The Unified Sensor library is a helper library for the DHT library.

Pete.