[SOLVED] "Failed to read from DHT sensor!"

dht22
esp8266
#1

Hi, I’m trying to read the temperature and humidity with this code, but I can not read it, because it only shows this error. If anyone can help me, I’ll be very grateful.

https://gist.githubusercontent.com/LosantGists/1c76d04c0e567852c416d6dd7b1fa87b/raw/38225afa6feca0513299c5e2da485515e52505fe/esp8266-dht22.ino

#2

Good morning @Luiz_Carlos_de_Azeve,

I am looking for just a bit more information to help find a solution to this. :smile:

Within the Getting Started with the ESP8266 and DHT22 Sensor blog post, there is a note before the code:

You’ll need to increase the underlying MQTT library’s memory limit. The PubSubClinet MQTT library has a default memory limit that is not enough to support all the values that the DHT22 sensor can collect. The error is also not apparent, which makes it hard to track. To increase the memory limit, please check out this forum post.

If you have not completed this step, errors can arise. If you have completed this step, and are still getting the error, let me know and we will try again!

Thanks,
Julia

#3

Hello, Julia. I also tried this step, and the error continues.

#4

Hello,

I need some more information to assist with this. Could you provide a screenshot of your serial monitor? And, if possible, a picture of the board wiring?

Thanks!
Julia

#5

I’m at my job now, so when I come back to my home, I’ll send these informations to you. Thank you, very much.

#6

But considering that everything is right, what I believe you are, do you think it can be what? :thinking:

#7

Hey @Louis_Bathalon,

That error is caused by this line:

// 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!");
      timeSinceLastRead = 0;
      return;
    }

Which is simply checking if the values from the sensor are numbers. There are many reasons why this could be failing. Some I can think of:

  • Incorrect Wiring
  • Wrong DHTPIN or DHTTYPE

If you have an issues with the library, i’d recommend opening an issue on Github:

There are also some examples there that may be able to help you.

#8

I uninstalled all the libraries and reinstalled again. I changed the value from 128 to 256 in the “MQTT_MAX_PACKET_SIZE” and it continues the same thing.

#9

The error “Failed to read from DHT Sensor” is only in Losant code, because I already tested the sensor with an arduino example code and it worked normal, only with this code that gives this error. I used the exemple “DHTtest.ino” and it shows this:

#10

Hey @Luiz_Carlos_de_Azeve,

Unfortunately, it’s hard to debug an issue like this on our end. Generally, we can help to get the device connected to Losant. Typically, our users get things working on the hardware side of things.

A couple of things I can recommend though:

I wrote that original article. I didn’t write the sensor code, though. I was able to use this as a starting point and then wrap the Losant connection code around it:

If you were able to get things working, I’d recommend you can take that same approach. If you have working code, all you need to do add the Losant Connection code.

In our repo, we provide an example here:

I don’t quite know why your example code works and the example you provided from us didn’t work. That could be for a number of reasons. But, if you got the sensor reading, all you need to do is add in the Losant connection code.

#11

Good evening, my friends.

Finally I did, I did what @anaptfox said, I inserted the Losant in the example that worked with me and it worked perfectly. Thanks so much for the help, I was thinking that I would not be able to. You are the best! That is the code:

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h"

#define DHTPIN 2     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

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

#include <ESP8266WiFi.h>
#include <Losant.h>

// WiFi credentials.
const char* WIFI_SSID = "WIFI_SSID";
const char* WIFI_PASS = "WIFI_PASS";

// Losant credentials.
const char* LOSANT_DEVICE_ID = "ID";
const char* LOSANT_ACCESS_KEY = "KEY";
const char* LOSANT_ACCESS_SECRET = "SECRET";

const int BUTTON_PIN = 14;
const int LED_PIN = 12;

bool ledState = false;

WiFiClient wifiClient;

// For an unsecure connection to Losant.
// WiFiClient wifiClient;

LosantDevice device(LOSANT_DEVICE_ID);

void toggle() {
  Serial.println("Toggling LED.");
  ledState = !ledState;
  digitalWrite(LED_PIN, ledState ? HIGH : LOW);
}

// Called whenever the device receives a command from the Losant platform.
void handleCommand(LosantCommand *command) {
  Serial.print("Command received: ");
  Serial.println(command->name);

  if(strcmp(command->name, "toggle") == 0) {
    toggle();
  }
}

void connect() {

  // Connect to Wifi.
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  WiFi.begin(WIFI_SSID, WIFI_PASS);

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

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

  // Connect to Losant.
  Serial.println();
  Serial.print("Connecting to Losant...");

  device.connect(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  // For an unsecure connection.
  // device.connect(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  while(!device.connected()) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("Connected!");
}

void setup() {
  Serial.begin(115200);
  Serial.println(F("DHTxx test!"));

  dht.begin();

  while(!Serial) { }
  pinMode(BUTTON_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  // Register the command handler to be called when a command is received
  // from the Losant platform.
  device.onCommand(&handleCommand);

  connect();
}

void buttonPressed() {
  Serial.println("Button Pressed!");

  // Losant uses a JSON protocol. Construct the simple state object.
  // { "button" : true }
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["button"] = true;

  // Send the state to Losant.
  device.sendState(root);
}

int buttonState = 0;

void report(double humidity, double tempC, double tempF, double heatIndexC, double heatIndexF) {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["humidity"] = humidity;
  root["tempC"] = tempC;
  root["tempF"] = tempF;
  root["heatIndexC"] = heatIndexC;
  root["heatIndexF"] = heatIndexF;
  device.sendState(root);
  Serial.println("Reported!");
}

int timeSinceLastRead = 0;

void loop() {
  // Wait a few seconds between measurements.
  
   bool toReconnect = false;

  if(WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi");
    toReconnect = true;
  }

  if(!device.connected()) {
    Serial.println("Disconnected from Losant");
    Serial.println(device.mqttClient.state());
    toReconnect = true;
  }

  if(toReconnect) {
    connect();
  }

  device.loop();

  int currentRead = digitalRead(BUTTON_PIN);

  if(currentRead != buttonState) {
    buttonState = currentRead;
    if(buttonState) {
      buttonPressed();
    }
  }

  delay(100);
  
 // Report every 2 seconds.
  if(timeSinceLastRead > 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!");
      timeSinceLastRead = 0;
      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");
    report(h, t, f, hic, hif);

    timeSinceLastRead = 0;
  }
  delay(100);
  timeSinceLastRead += 100;
}
2 Likes