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

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.


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!


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


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?


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.

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

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;

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

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.

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.

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:

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.

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.

#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 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: ");

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

void connect() {

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


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

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

  // Connect to Losant.
  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()) {


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


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

  // Register the command handler to be called when a command is received
  // from the Losant platform.


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.

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;

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");
    toReconnect = true;

  if(toReconnect) {


  int currentRead = digitalRead(BUTTON_PIN);

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

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

    // 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(" %\t");
    Serial.print("Temperature: ");
    Serial.print(" *C ");
    Serial.print(" *F\t");
    Serial.print("Heat index: ");
    Serial.print(" *C ");
    Serial.println(" *F");
    report(h, t, f, hic, hif);

    timeSinceLastRead = 0;
  timeSinceLastRead += 100;

Remember la pin number in you code it not the same than phisical pin. For example on the board say D2 but go like GPIO4!!! I adjut the image

Diging this up, because I had the same problem.

I think the problem is that the examples are missing the line:

Adding that line fixed the problem.