Dht22 nan ошибка

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

robcazzaro opened this issue

Nov 26, 2017

· 41 comments

Comments

@robcazzaro

I’m using a few Wemos D1 and generic ESP8266-12 as temperature/humidity sensors feeding data to a service. All the ESP8266 devices are plain vanilla, and I use default settings when compiling.The DHT22 is connected to GPIO12, and I invoke the DHT library with

#define DHTPIN 12
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE, 15); //15 critical to stable readings

I have been using them for at least 2 years, using the original 1.0.0 DHT library, with no problems at all. I read the temperature/humidity every 10 seconds

I recently updated my devices with a newer version of my code, and I used Arduino 1.8.5 with newer libraries to ensure I have the latest and best. Same devices, same code. I immediately started getting a lot of NAN returned by the DHT library, and my devices skip roughly 15-20% of the reading cycles as a result.

After a long troubleshooting sessions, I narrowed the problem down to the DHT library version. With any version older than 1.2.0, everything works just fine. As soon as I use a newer library, I get the NAN errors. It looks as if the timing optimization in 9d7a9da (the one that deprecated the parameter count, 15 in my case) doesn’t work properly with the DHT22 and ESP8266 I’m using. There is a subtle timing error that at least in my case throws off some readings

I searched online for a similar issue, and found a lot of people with DHT22 and NAN issues, but none seemed to truly apply

It’s hard to believe this issue was not discovered in ~2 years, but I have a solid repro in 4 devices at least, and I discovered it only because my code logs NAN results, while most people tend to write code that in case of a NAN repeats the DHT read right away, so might be masked

@khjoen

it seems this is starting of death or end of life for this lib. Not much
support for fundamental problems

Happy to help if anyone is ready to fork.

On 25 November 2017 at 22:00, robcazzaro ***@***.***> wrote:
I’m using a few Wemos D1 and generic ESP8266-12 as temperature/humidity
sensors feeding data to a service. All the ESP8266 devices are plain
vanilla, and I use default settings when compiling.The DHT22 is connected
to GPIO12, and I invoke the DHT library with

#define DHTPIN 12
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE, 15); //15 critical to stable readings

I have been using them for at least 2 years, using the original 1.0.0 DHT
library, with no problems at all. I read the temperature/humidity every 10
seconds

I recently updated my devices with a newer version of my code, and I used
Arduino 1.8.5 with newer libraries to ensure I have the latest and best.
Same devices, same code. I immediately started getting a lot of NAN
returned by the DHT library, and my devices skip roughly 15-20% of the
reading cycles as a result.

After a long troubleshooting sessions, I narrowed the problem down to the
DHT library version. With any version older than 1.2.0, everything works
just fine. As soon as I use a newer library, I get the NAN errors. It looks
as if the timing optimization in

9d7a9da

<

9d7a9da

>
(the one that deprecated the parameter count, 15 in my case) doesn’t work
properly with the DHT22 and ESP8266 I’m using. There is a subtle timing
error that at least in my case throws off some readings

I searched online for a similar issue, and found a lot of people with
DHT22 and NAN issues, but none seemed to truly apply

It’s hard to believe this issue was not discovered in ~2 years, but I have
a solid repro in 4 devices at least, and I discovered it only because my
code logs NAN results, while most people tend to write code that in case of
a NAN repeats the DHT read right away, so might be masked


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#94>, or mute the
thread
<https://github.com/notifications/unsubscribe-auth/ALSrTQ0REpdy4RqdwlPjPDRL6D7mbuJKks5s6NRjgaJpZM4Qqo1J>
.

@robcazzaro

It turns out I did not discover something new: as I suspected, this is a well known and already reported issue (in many forums), one that has already been discussed and a solution is available. What is puzzling, is why this has not been addressed yet, at least for the ESP8266 platform. Even the frequency of the problem as previously reported matches mine

Here’s the best link to explain the problem: #48

And the solution is as simple as commenting out two lines (line 155 and 156 of the current library), and avoiding having the processor force the data line high on the DHT22:

// End the start signal by setting data line high for 40 microseconds.

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

I have made that change in my local copy of the library, and so far have been reading hundreds of samples on 4 boards, not a single error. It’s not what I would consider a solid proof yet, but with the un-modified 1.3.0 version I would never have been able to read this many samples without problems

I strongly recommend checking in the fix, if needed in a conditional block for the ESP8266 only (I cannot test on other processors, but I’m sure it’s required for the ESP8266… and, based on the original description and the DHT22 datasheet, a required fix for all)

@beicnet

@robcazzaro Yeah, same issue with me yesterday, but don’t forget to change bellow that code:

pinMode(_pin, INPUT_PULLUP);
delayMicroseconds(10);

change delay to from 10 to 50

@robcazzaro

In my case the change from 10 to 50 doesn’t seem necessary, works both way, but I changed it anyway to 50. Thanks for the suggestion, @beicnet

At this point I have ~10k readings, not a single NAN… Pretty confident that this change is needed and much safer than the code currently in the library

I’m leaving this issue open (even if I have a fix now), for future consideration

@beicnet

@robcazzaro I did the same thing by others proposition, so, I think it will not hurt anyway! Kappa

@ronalLeiva

@captainju

@Salty-Doug

I am new to Arduino and microcontrollers. I had the nan problem with an ESP32 & DHT22 in Arduino IDE. I commented out the two lines above in DHT.cpp but when I downloaded the code I only saw «nan». Any ideas?

@robcazzaro

Methinks that the timing of the much faster ESP32 does not work well with the DHT22 timing. I have really grown to dislike the DHT22, too sensitive to even small changes, and the protocol requires precise bitbanging

You could use the newer AM2320, which works with I2C protocols instead, and costs even less than a DHT22. I2C is much more reliable on all processors

@Salty-Doug

Thanks captainju, I used the DHTstable library on my ESP32 and I am not seeing anymore «nan» readings.

@VikIborra

I think that the problem is in the Chip.
Last days I’ve received from China models of DHT22 with Chip ASAIR and is not 100% compatible. AOSONG is very good but ASAIR has problems.

@robcazzaro

Try a different library, and you’ll see it works. This library has a known bug and it’s too timing dependent for modern IoT boards with different processors. It worked fine as long as everyone used the slow, original Arduino. You might also have a bad chip, but in my case (and many others) using a different library or patching the code bug solved the problem easily. It’s not a chip problem

@VikIborra

With Wemos D1 Mini (v2.0, 2.2, 2.3, 3.0) doesn’t work.
I’ve tried with diferent resistors, voltage (3.3/5), shield pro (dht22), … only when I use AOSONG in same PCB Shield Pro received with ASAIR, works. I desolder ASAIR and I put AOSONG.
I have tried all libraries in platformio.
Same PCB with Arduino UNO, works but not in Wemos D1 Mini.
70% of ASAIR, fails by time out.
I have changed «const int DHTLIB_TIMEOUT» in dht.h but nothing result.
Thanks in advance.

@robcazzaro

Have you tried commenting out the two lines 155-6 (and recompiling the library), as explained above in this thread? And possibly changing the delay from 10 to 50.

Without those changes, not even a DHT22 worked for me

In any case, the newer AM2320 is a much better choice these days :) or for overkill, a BME20, which also measures pressure

@VikIborra

With PlatformIO and Libraries «DHT sensor library 1.3.0» and «Adafruit Unified Sensor 1.0.2».

Using example code : «DHT_Unified_Sensor»
Change to: «DHT_Unified dht(DHTPIN, DHTTYPE, 50);» and 15
Comment lines in DHT.cpp: (155-156)
// digitalWrite(_pin, HIGH);
// delayMicroseconds(40);

I get good values 30% of times when I power off-on the wemos d1 mini, but never works when I use reset button or DEEP_SLEEP. It’s very unstable.
Any idea?

Thx in advance,

@robcazzaro

In my case, the DHT22 sensors were very sensitive to RF noise from the ESP8266. With different ESP8266 modules, wiring and power supplies, I had all sort of weird problems, which also changed depending on which version of the Arduino ESP8266 core I used. DEEP_SLEEP also caused weird RF behavior which in turn caused problems.

My suggestions is to try different libraries like https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTstable and in the future stop using DHT22 and use the AM2320 instead (they cost more or less the same)

@VikIborra

@alexandruoliva

@davejel

Hi all
I know this is an old thread but i’ll put this solution here for anyone else having problems.
i was also having the same problem with NAN errors using ESP8266-01 with DHT22, i tried pins: GPIO2, 3
Power cycling makes the sensor read normally !!!! ( i tried several different libs)
After using a scope to watch the pins during upload both pins 2 & 3 have data at upload time which of course is not there if you power cycle
My solution is to connect ground on DHT22 to GPIO0 which is held high at upload time.
AND in setup before initializing DHT22 three lines:

digitalWrite(0, LOW); // sets output to gnd
pinMode(0, OUTPUT); // switches power to DHT on
delay(1000); // delay necessary after power up for DHT to stabilize

This works with all the libs i tried which were not working before. it appears that the data was scrambling the DHT’s brain with the power on all of the time

cheers
Dave

@sergio-daniels

It turns out I did not discover something new: as I suspected, this is a well known and already reported issue (in many forums), one that has already been discussed and a solution is available. What is puzzling, is why this has not been addressed yet, at least for the ESP8266 platform. Even the frequency of the problem as previously reported matches mine

Here’s the best link to explain the problem: #48

And the solution is as simple as commenting out two lines (line 155 and 156 of the current library), and avoiding having the processor force the data line high on the DHT22:

// End the start signal by setting data line high for 40 microseconds.

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

I have made that change in my local copy of the library, and so far have been reading hundreds of samples on 4 boards, not a single error. It’s not what I would consider a solid proof yet, but with the un-modified 1.3.0 version I would never have been able to read this many samples without problems

I strongly recommend checking in the fix, if needed in a conditional block for the ESP8266 only (I cannot test on other processors, but I’m sure it’s required for the ESP8266… and, based on the original description and the DHT22 datasheet, a required fix for all)

Thanks, worked for me as well

@ghost

I have a Wemos D1 R2 board and DHT22. None of the solutions given here are working for me.

@robcazzaro

As I said before, I highly recommend to use better sensors than a DHT22, these days. The DHT22 is one of the most finicky thermo/humidity sensors out there

Having said that, though, the workaround I mention here works on just about any Wemos boards.

What do you mean «not working»? The original library works, just with too man NAN errors. If you don’t get anything at all, the problem lies elsewhere, and I suggest you troubleshoot it one step at a time and possibly ask for help in another, more appropriate, forum (this is really not a support forum)

@ghost

I have changed the sensor and I am using LM35 Temperature Sensor now. I have connected the ‘Out’ Pin of sensor to Pin A0 of Wemos D1 R2 for Analog reading. Before doing this I tested the A0 pin with following piece of code:

long int reading = 0;
float avg = 0.0;
void setup()
{
    Serial.begin(9600);
}
void loop() 
{
    for(int i = 0; i < 10; i++)
    {
        reading += analogRead(A0);
        delay(50);
    }
    avg = reading/10.0; 
    reading = 0; 
    Serial.print("Average Count: ");
    Serial.print(avg);
    delay(1000);
}

This code works quite well for potentiometer with full reading range from 0 to 1024 for a 0-3.3 V range. The same code does not give count at all for LM35 which is already tested OK with Arduino Uno. I know that LM35 is having operating voltage range of 4-30 V and that is why I connected it to the 5 V pin of Wemos D1 R2 because it would not harm the Wemos as the analog voltage transduced from nearly 26 degree Celsius at my place, would not exceed 3.3 V level of Wemos. The count remains in between 0 and 5 as per the code. I have also tested the same sensor on fresh Wemos D1 R2 board where I observed the same issue. So I am reporting this bug of LM35 error with Wemos. Kindly help.

Shaunak Agastya Vyas

@robcazzaro

This is not a support forum, please ask your questions in the right forum (Wemos or ESP8266 Arduino

Closing this issue to avoid further unrelated questions

@ghost

The issue is not resolved yet. DHT22 Sensor is not working with Wemos for me even after trying all the solutions given here. The way I have described the issue with LM35 speaks that I am not just an another beginner. Now, please solve both the issues of DHT22 and LM35. I am not a rebellion, so please do not block me on GitHub. I am just an idiot who is stuck up and needs help badly.

Shaunak Agastya Vyas

@ghost
ghost

mentioned this issue

Nov 29, 2018

@khjoen

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

@j-opificius

My solution is to connect ground on DHT22 to GPIO0 which is held high at upload time.
AND in setup before initializing DHT22 three lines:

digitalWrite(0, LOW); // sets output to gnd
pinMode(0, OUTPUT); // switches power to DHT on
delay(1000); // delay necessary after power up for DHT to stabilize

This solution in conjunction with the two line fix to the library works for me so far, with a sample of one. My device is an ASAIR AM2302 hard wired onto a 3-pin adapter board with a 4k7 pull-up from data output to +ve and a cap across power.
It came up with no coaxing after a software upload for each of 10 attempts, and also after several simple power cycles (no upload) using a micro-USB source.
I’m going to build 8 units of this config, each powered from a 2 x AA 3V power source. I’ll report if there are any issues.

@yavimaya

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

That worked flawlessly on a ESP32 and dht22.
No errors at all.
Thank you!!

@teverth

In my case, I am using two DHT22 on an ESP32 and was getting lots of NAN readings like the others. I am using the currently published DHT22 library from the Adafruit website.
I tracked the issue down to checksum errors. And in fact, what it was is that from time to time the highest bit on the checksum transmitted by the DHT22 was not set to «1» when it had to. All other bits coming from the DHT22 matched what the checksum needed to be. So now I am masking the checksum check with 0x7F instead of 0xFF and presto: Not a single NAN result anymore.

Before that change, I also followed the recommendations above to comment out the two lines below and change the value to 50 in the last line of this part:

//digitalWrite(_pin, HIGH); 
//delayMicroseconds(40);  

// Now start reading the data line to get the value from the DHT sensor.
pinMode(_pin, INPUT_PULLUP);
delayMicroseconds(50);  // Delay a bit to let sensor pull data line low.

But these changes alone did not fix the checksum issue and are possibly not related in my case to the solution. But masking for 0x7F did the trick, see below.

DEBUG_PRINTLN(F(«Received:»));
DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[4] & 0x7F, HEX); DEBUG_PRINT(F(» =? «));
DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0x7F, HEX);

// Check we read 40 bits and that the checksum matches.
if ((data[4] & 0x7F) == ((data[0] + data[1] + data[2] + data[3]) & 0x7F)) {
_lastresult = true;
return _lastresult;
}
else {
DEBUG_PRINTLN(F(«Checksum failure!»));
_lastresult = false; // set to true to ignore checksum err
return _lastresult;
}

I also so other people posting their NAN issues and saw that they had the very same mismatch of the checksums, i.e.: Calculated checksum byte = 0xCA but received checksum byte = 4A, the high bit missing.
I think that perhaps the DHT22 signals something else with that top checksum bit that they don’t tell us in the datasheet? But ignoring that bit does no harm. The values that I get from my DHT22 sensors are all good and matching with independently measured values. So this fix sorted it all for me.

@DIYGuy01

did not help me. Still nan
ESP01 + AOSONG AM2302

But it works absolutely fine on Arduino Uno with the same lib

@khjoen

@DIYGuy01

I was trying 3 days to achieve working DHT22 AOSONG with ESP-01 without success, trying various libs, changes in them, power source, boards, sensors etc.
9 months ago I made sketch the same ESP-01 with ASAIR DHT22 and it was working fine until this moment when I recompiled and changed DHT22 sensor vendor (I think during this time libs also have changed).
New setup is working fine with Arduino Uno and Wemos D1 mini, but not with ESP-01. With debug on was getting constantly «DHT timeout waiting for start signal high pulse.»
Until I tried one trick which I found here on Github (do not remember where)
Simple:

Void setup() {  
// workaround for DHT22 due to NAN error
  digitalWrite(DHTPIN, LOW); // sets output to gnd
  pinMode(DHTPIN, OUTPUT); // switches power to DHT on
  delay(1000); // delay necessary after power up for DHT to stabilize
  dht.begin();
....

dhd.begin() should follow instantly. If you put it in pre setup section- won’t work.
It works 100% not missing any reading in my case also ESP-01 is used with deepsleep().

This workaround helped me. Not going to deep dive in libs, I’ve got working solution but I hope it will give you direction what is wrong with lib, timings or new generation of chinese sensors :)

@netixx

I have the ASAIR AM2302 (with shield and pull-up) and Wemos D1 mini (v3.0.0) and I can confirm @VikIborra suggestion to use D3 instead of the pre-wired D4 in the shield I received with it. I am using the latest v1.3.3 which has been published with fixes yesterday. With D4 I wasn’t able to read any data at all!

I am still getting a few NAN, every 15 measurement or so using the test sketch provided with the library.

@fabiom91

// digitalWrite(_pin, HIGH);
// delayMicroseconds(40);

Hi @robcazzaro I cannot find the two lines you quoted:

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

In which file are them? .-.

@robcazzaro

This issue was opened on version 1.2.0 of the library, in 2017. The current version of the library has changed a lot, and according to the comments for release 1.3.2, the ESP8266 timing issues have been addressed. So probably nothing here applies anymore :)

@korovinn

Work for me.
Try to do these:

  1. Connect DHT22 «+» to D0 on esp8266 and NOT to 3,3v
  2. Connect DHT22 «out» to D3 on esp8266
  3. Use such code in void setup ()

void setup()
{
Serial.begin(115200);
pinMode(DHTPin, INPUT);
pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
dht.begin();
timer.setInterval(5000L, getdata);
}

@pentiumduck

Your code fixed this issue. Thank you !!!

@sheepsy90

That helped! Old lib works! It’s a start!

@fontanon

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

Worked like a charm to me with Heltec WiFi LoRa 32 + DHT22 (AM23D2). I came from this tutorial: https://github.com/enzof6/arduino-lmic-for_ESP32 and end up with the NaN reading errors. Thanks for sharing.

fontanon

added a commit
to ttn-sevilla/arduino-lmic-for_ESP32
that referenced
this issue

Aug 1, 2020

@fontanon

@boumanb

Work for me.
Try to do these:

1. Connect DHT22 "+" to D0 on esp8266 and NOT to 3,3v

2. Connect DHT22 "out" to D3 on esp8266

3. Use such code in void setup ()

void setup()
{
Serial.begin(115200);
pinMode(DHTPin, INPUT);
pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
dht.begin();
timer.setInterval(5000L, getdata);
}

Thank you. Any explanation?

@GreaseMonkey88

I had the same problem using a DHT22/ESP8266(WemosD1Mini) for outdoor measurements connected to the 3.3V pin. After 24h or sometimes just hours I got NaN readings. So I sent the MCU to sleep for just 45s around every hour — that seems to work so far:

if (millis() >= 3600e3) // DeepSleep to "reset" the DHT22 sensor. Connect pins D0 + RST
  {
    ESP.deepSleep(45e6);
  }

Страница 1 из 2

  1. Решил сделать бота, который будет отправлять данные с датчика в Телеграм
    Написал код, всё в принципе работает
    Но одна проблема — датчик отправляет данные «NaN»
    То есть по сути ничего не отправляет.
    Если накатить DHTtest на ESP32, то датчик работает, изредка «отваливаясь»
    А на прошивке с ботом не работает по сути вообще.
    У меня есть подозрения что это из-за перевода float данных с датчика в string, чтобы отправить их в Телеграм
    Подскажите, как можно это исправить

    #include «DHT.h»
    #define DHTPIN 5
    #define DHTTYPE DHT22
    #include <WiFi.h>
    #include <WiFiClientSecure.h>
    #include <UniversalTelegramBot.h>

    // Wifi network station credentials
    #define WIFI_SSID «FU12 YO2U»
    #define WIFI_PASSWORD «716530544AA»
    // Telegram BOT Token (Get from Botfather)
    #define BOT_TOKEN «1953777245:AAFGZeZj4l807jA02sXjaY0d4aS-R-WmYYa»

    const unsigned long BOT_MTBS = 1000; // mean time between scan messages

    WiFiClientSecure secured_client;
    UniversalTelegramBot bot(BOT_TOKEN, secured_client);
    unsigned long bot_lasttime;          // last time messages’ scan has been done
    bool Start = false;

    DHT dht(DHTPIN, DHTTYPE);

    void handleNewMessages(int numNewMessages)
    {

     
      Serial.println(«handleNewMessages»);
      Serial.println(String(numNewMessages));

      for (int i = 0; i < numNewMessages; i++)
      {
        String chat_id = bot.messages[i].chat_id;
        String text = bot.messages[i].text;

        String from_name = bot.messages[i].from_name;
        if (from_name == «»)
          from_name = «Guest»;

        if (text == «/send_test_action»)
        {
          bot.sendChatAction(chat_id, «typing»);
          delay(4000);
          bot.sendMessage(chat_id, «Did you see the action message?»);
        }
        int a = 1;
        while(a = 1)
       {
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          Serial.print(F(«Humidity: «));
          Serial.print(h);
          Serial.print(F(«%  Temperature: «));
          Serial.print(t);
          String message = «Humidity: « + String(h) + »  Temperature: « + String(t);
          bot.sendMessage(chat_id, message);
      }
    }
    }
    void setup()
    {
      Serial.begin(115200);
      Serial.println();

      // attempt to connect to Wifi network:
      Serial.print(«Connecting to Wifi SSID «);
      Serial.print(WIFI_SSID);
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print(«.»);
        delay(500);
      }
      Serial.print(«\nWiFi connected. IP address: «);
      Serial.println(WiFi.localIP());

      Serial.print(«Retrieving time: «);
      configTime(0, 0, «pool.ntp.org»); // get UTC time via NTP
      time_t now = time(nullptr);
      while (now < 24 * 3600)
      {
        Serial.print(«.»);
        delay(100);
        now = time(nullptr);
      }
      Serial.println(now);
    }

    void loop()
    {
      if (millis() bot_lasttime > BOT_MTBS)
      {
        int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

        while (numNewMessages)
        {
          Serial.println(«got response»);
          handleNewMessages(numNewMessages);
          numNewMessages = bot.getUpdates(bot.last_message_received + 1);
        }

        bot_lasttime = millis();
      }
    }

  2. ТС, по ходу, где-то тиснул код. Никаких NaN DHT22 отправлять не способен. А проблема в соплях к датчику.

  3. Код ниоткуда не тискал, соединил то что мне нужно с примером кода для бота, не более.
    Даже в монитор порта DHT22 отправляет NaN.
    Миллион тем по этому поводу в интернете, но ни одно решение мне не помогло. Провода меняю уже не знаю какой раз.
    [​IMG]
    Сейчас начали изредка приходить данные, но неправильные
    В комнате у меня температура около 27, никак не 13.
    Вероятно моё предположение по поводу типов переменных не верно.
    В чём тогда может быть проблема ещё? Всё таки в проводах?

  4. Так вот и разберись, кто формирует NaN. Это точно не датчик — в его даташите об этом ничего не сказано.

  5. когда говорят «в принципе работает» — обычно это значит, что либо работает через пень колоду, либо не работает вовсе.
    Ваш код — отличный этому пример.
    Как вы думаете. сколько раз выполнится этот цикл?

    int a = 1;
        while(a = 1)
       {
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          Serial.print(F(«Humidity: «));
          Serial.print(h);
          Serial.print(F(«%  Temperature: «));
          Serial.print(t);
          String message = «Humidity: « + String(h) + »  Temperature: « + String(t);
          bot.sendMessage(chat_id, message);
      }
  6. Бесконечный цикл, специально его сделал, чтобы данные регулярно прилетали в Телеграм сами.

  7. В принципе работает — данные прилетают в Телеграм, но какие это данные?
    Верно, NaN.
    Как исправить — не пойму, провода в очередной раз поменял раз 5.
    Пины поменял раз 5.
    Изредка прилетают данные и то, неправильные. Температура как будто поделена на 2.
    Влажность — тоже.
    Пока других вариантов исправления никто не подкинул.

  8. дядя. ты дурак? (с)
    Чтобы программа работала, функция handleNewMessages() должна обработать сообщение и передать управление основному коду. А у вас при первом же сообщении программа зависает в бесконечном цикле навсегда…
    И вы удивляетесь, почему ничего не отсылается? :)

    И еще — посмотрите в описании — насколько часто можно опрашивать датчик DHT22 ? сдается мне, что он у вас просто перестает отдавать реальные даннные из-за слищком частых опросов. Опрашивайте его не чаще 1 раза в секунду. а не долбите бесконечно, как у вас в коде

    Последнее редактирование: 30 авг 2021

  9. Я не совсем разбираюсь в Telegram Bot API, можно сказать вообще не разбираюсь
    Как обработка сообщения может повлиять на передачу данных с датчика?
    Работа происходит в цикле, показания снялись — отправились, снялись — отправились
    Команды никакие не заданы для работы бота, он сам начинает просто писать
    Как это может быть связано с обработкой сообщения?
    Delay стоит 2000, дефолтный для DHT22, в коде том экспериментировал просто, убрал его, а так в начали цикла стоит

  10. Что такое while (a=1)? Это присвоение а значение 1 . Условие будет истинно ВСЕГДА!Этот блок кода будет выполниться бесконечно и программа зациклиться. Может надо while (a==1)?

  11. не знаю, где он у вас стоит, в этом коде его нет и датчик долбится непрерывно.

    Простите, вы сюда спорить пришли? — если да, решайте свои проблемы сами.

  12. В каком месте я пытаюсь спорить? Я пытаюсь выяснить как это может быть связано. Я сюда пришёл за помощью, не более. Если это как-то связано — прошу пояснить как.

  13. В сторону проводов тоже по сути думать невозможно. В DHTtest’e данные приходят нормально. А тут — NaN, делённые на два или температура 3000.

  14. А зачем так часто лупить? Ядерные исследования? Температуру достаточно снимать один раз в минуту. И то для тупого DHT22 даже это очень часто — температура не может меняться так быстро,
    чтобы она ушла за пределы чувствительности этого датчика.

  15. Просто когда вывожу в консоль бывает по нескольку раз не выдаёт показания, сделаю delay минуту и считай есть вероятность того что показаний не будет и 5 и 10 минут.
    Делаю чаще показания — раз в 2 секунды, показания приходят примерно 60/100
    Тут же и в том и том варианте показания вообще по сути не приходят.

  16. Oyage,

    в том вашем чудесном цикле while(), что мы обсуждаем — я вижу у вас данные одновременно выводятся в Сериал и отправляются в бот. Скажите — эти данные (в сериале и боте) -отличаются?
    Если нет — и там и там NAN — то код бота вообще не причем и вы просто неверно работаете с датчиком.

  17. Да, и там и там NaN, а в чём может быть проблема работы с датчиком? По сути часть работы датчика скопирована из DHTtest’a.

  18. в первую очередь попробуйте его опрашивать пореже, как уже не раз вам советовали
    Если не поможет — соберите схему отдельно, залейте готовый пример из библиотеки, без всяких ботов — и проверьте. чтобы датчик работал устойчиво. Если заработает — постепенно добавляйте код для бота

  19. Уже проверял — всё работает исправно.

Страница 1 из 2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

robcazzaro opened this issue

Nov 26, 2017

· 41 comments

Comments

@robcazzaro

I’m using a few Wemos D1 and generic ESP8266-12 as temperature/humidity sensors feeding data to a service. All the ESP8266 devices are plain vanilla, and I use default settings when compiling.The DHT22 is connected to GPIO12, and I invoke the DHT library with

#define DHTPIN 12
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE, 15); //15 critical to stable readings

I have been using them for at least 2 years, using the original 1.0.0 DHT library, with no problems at all. I read the temperature/humidity every 10 seconds

I recently updated my devices with a newer version of my code, and I used Arduino 1.8.5 with newer libraries to ensure I have the latest and best. Same devices, same code. I immediately started getting a lot of NAN returned by the DHT library, and my devices skip roughly 15-20% of the reading cycles as a result.

After a long troubleshooting sessions, I narrowed the problem down to the DHT library version. With any version older than 1.2.0, everything works just fine. As soon as I use a newer library, I get the NAN errors. It looks as if the timing optimization in 9d7a9da (the one that deprecated the parameter count, 15 in my case) doesn’t work properly with the DHT22 and ESP8266 I’m using. There is a subtle timing error that at least in my case throws off some readings

I searched online for a similar issue, and found a lot of people with DHT22 and NAN issues, but none seemed to truly apply

It’s hard to believe this issue was not discovered in ~2 years, but I have a solid repro in 4 devices at least, and I discovered it only because my code logs NAN results, while most people tend to write code that in case of a NAN repeats the DHT read right away, so might be masked

@khjoen

it seems this is starting of death or end of life for this lib. Not much
support for fundamental problems

Happy to help if anyone is ready to fork.

On 25 November 2017 at 22:00, robcazzaro ***@***.***> wrote:
I’m using a few Wemos D1 and generic ESP8266-12 as temperature/humidity
sensors feeding data to a service. All the ESP8266 devices are plain
vanilla, and I use default settings when compiling.The DHT22 is connected
to GPIO12, and I invoke the DHT library with

#define DHTPIN 12
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE, 15); //15 critical to stable readings

I have been using them for at least 2 years, using the original 1.0.0 DHT
library, with no problems at all. I read the temperature/humidity every 10
seconds

I recently updated my devices with a newer version of my code, and I used
Arduino 1.8.5 with newer libraries to ensure I have the latest and best.
Same devices, same code. I immediately started getting a lot of NAN
returned by the DHT library, and my devices skip roughly 15-20% of the
reading cycles as a result.

After a long troubleshooting sessions, I narrowed the problem down to the
DHT library version. With any version older than 1.2.0, everything works
just fine. As soon as I use a newer library, I get the NAN errors. It looks
as if the timing optimization in

9d7a9da

<

9d7a9da

>
(the one that deprecated the parameter count, 15 in my case) doesn’t work
properly with the DHT22 and ESP8266 I’m using. There is a subtle timing
error that at least in my case throws off some readings

I searched online for a similar issue, and found a lot of people with
DHT22 and NAN issues, but none seemed to truly apply

It’s hard to believe this issue was not discovered in ~2 years, but I have
a solid repro in 4 devices at least, and I discovered it only because my
code logs NAN results, while most people tend to write code that in case of
a NAN repeats the DHT read right away, so might be masked


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#94>, or mute the
thread
<https://github.com/notifications/unsubscribe-auth/ALSrTQ0REpdy4RqdwlPjPDRL6D7mbuJKks5s6NRjgaJpZM4Qqo1J>
.

@robcazzaro

It turns out I did not discover something new: as I suspected, this is a well known and already reported issue (in many forums), one that has already been discussed and a solution is available. What is puzzling, is why this has not been addressed yet, at least for the ESP8266 platform. Even the frequency of the problem as previously reported matches mine

Here’s the best link to explain the problem: #48

And the solution is as simple as commenting out two lines (line 155 and 156 of the current library), and avoiding having the processor force the data line high on the DHT22:

// End the start signal by setting data line high for 40 microseconds.

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

I have made that change in my local copy of the library, and so far have been reading hundreds of samples on 4 boards, not a single error. It’s not what I would consider a solid proof yet, but with the un-modified 1.3.0 version I would never have been able to read this many samples without problems

I strongly recommend checking in the fix, if needed in a conditional block for the ESP8266 only (I cannot test on other processors, but I’m sure it’s required for the ESP8266… and, based on the original description and the DHT22 datasheet, a required fix for all)

@beicnet

@robcazzaro Yeah, same issue with me yesterday, but don’t forget to change bellow that code:

pinMode(_pin, INPUT_PULLUP);
delayMicroseconds(10);

change delay to from 10 to 50

@robcazzaro

In my case the change from 10 to 50 doesn’t seem necessary, works both way, but I changed it anyway to 50. Thanks for the suggestion, @beicnet

At this point I have ~10k readings, not a single NAN… Pretty confident that this change is needed and much safer than the code currently in the library

I’m leaving this issue open (even if I have a fix now), for future consideration

@beicnet

@robcazzaro I did the same thing by others proposition, so, I think it will not hurt anyway! Kappa

@ronalLeiva

@captainju

@Salty-Doug

I am new to Arduino and microcontrollers. I had the nan problem with an ESP32 & DHT22 in Arduino IDE. I commented out the two lines above in DHT.cpp but when I downloaded the code I only saw «nan». Any ideas?

@robcazzaro

Methinks that the timing of the much faster ESP32 does not work well with the DHT22 timing. I have really grown to dislike the DHT22, too sensitive to even small changes, and the protocol requires precise bitbanging

You could use the newer AM2320, which works with I2C protocols instead, and costs even less than a DHT22. I2C is much more reliable on all processors

@Salty-Doug

Thanks captainju, I used the DHTstable library on my ESP32 and I am not seeing anymore «nan» readings.

@VikIborra

I think that the problem is in the Chip.
Last days I’ve received from China models of DHT22 with Chip ASAIR and is not 100% compatible. AOSONG is very good but ASAIR has problems.

@robcazzaro

Try a different library, and you’ll see it works. This library has a known bug and it’s too timing dependent for modern IoT boards with different processors. It worked fine as long as everyone used the slow, original Arduino. You might also have a bad chip, but in my case (and many others) using a different library or patching the code bug solved the problem easily. It’s not a chip problem

@VikIborra

With Wemos D1 Mini (v2.0, 2.2, 2.3, 3.0) doesn’t work.
I’ve tried with diferent resistors, voltage (3.3/5), shield pro (dht22), … only when I use AOSONG in same PCB Shield Pro received with ASAIR, works. I desolder ASAIR and I put AOSONG.
I have tried all libraries in platformio.
Same PCB with Arduino UNO, works but not in Wemos D1 Mini.
70% of ASAIR, fails by time out.
I have changed «const int DHTLIB_TIMEOUT» in dht.h but nothing result.
Thanks in advance.

@robcazzaro

Have you tried commenting out the two lines 155-6 (and recompiling the library), as explained above in this thread? And possibly changing the delay from 10 to 50.

Without those changes, not even a DHT22 worked for me

In any case, the newer AM2320 is a much better choice these days :) or for overkill, a BME20, which also measures pressure

@VikIborra

With PlatformIO and Libraries «DHT sensor library 1.3.0» and «Adafruit Unified Sensor 1.0.2».

Using example code : «DHT_Unified_Sensor»
Change to: «DHT_Unified dht(DHTPIN, DHTTYPE, 50);» and 15
Comment lines in DHT.cpp: (155-156)
// digitalWrite(_pin, HIGH);
// delayMicroseconds(40);

I get good values 30% of times when I power off-on the wemos d1 mini, but never works when I use reset button or DEEP_SLEEP. It’s very unstable.
Any idea?

Thx in advance,

@robcazzaro

In my case, the DHT22 sensors were very sensitive to RF noise from the ESP8266. With different ESP8266 modules, wiring and power supplies, I had all sort of weird problems, which also changed depending on which version of the Arduino ESP8266 core I used. DEEP_SLEEP also caused weird RF behavior which in turn caused problems.

My suggestions is to try different libraries like https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTstable and in the future stop using DHT22 and use the AM2320 instead (they cost more or less the same)

@VikIborra

@alexandruoliva

@davejel

Hi all
I know this is an old thread but i’ll put this solution here for anyone else having problems.
i was also having the same problem with NAN errors using ESP8266-01 with DHT22, i tried pins: GPIO2, 3
Power cycling makes the sensor read normally !!!! ( i tried several different libs)
After using a scope to watch the pins during upload both pins 2 & 3 have data at upload time which of course is not there if you power cycle
My solution is to connect ground on DHT22 to GPIO0 which is held high at upload time.
AND in setup before initializing DHT22 three lines:

digitalWrite(0, LOW); // sets output to gnd
pinMode(0, OUTPUT); // switches power to DHT on
delay(1000); // delay necessary after power up for DHT to stabilize

This works with all the libs i tried which were not working before. it appears that the data was scrambling the DHT’s brain with the power on all of the time

cheers
Dave

@sergio-daniels

It turns out I did not discover something new: as I suspected, this is a well known and already reported issue (in many forums), one that has already been discussed and a solution is available. What is puzzling, is why this has not been addressed yet, at least for the ESP8266 platform. Even the frequency of the problem as previously reported matches mine

Here’s the best link to explain the problem: #48

And the solution is as simple as commenting out two lines (line 155 and 156 of the current library), and avoiding having the processor force the data line high on the DHT22:

// End the start signal by setting data line high for 40 microseconds.

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

I have made that change in my local copy of the library, and so far have been reading hundreds of samples on 4 boards, not a single error. It’s not what I would consider a solid proof yet, but with the un-modified 1.3.0 version I would never have been able to read this many samples without problems

I strongly recommend checking in the fix, if needed in a conditional block for the ESP8266 only (I cannot test on other processors, but I’m sure it’s required for the ESP8266… and, based on the original description and the DHT22 datasheet, a required fix for all)

Thanks, worked for me as well

@ghost

I have a Wemos D1 R2 board and DHT22. None of the solutions given here are working for me.

@robcazzaro

As I said before, I highly recommend to use better sensors than a DHT22, these days. The DHT22 is one of the most finicky thermo/humidity sensors out there

Having said that, though, the workaround I mention here works on just about any Wemos boards.

What do you mean «not working»? The original library works, just with too man NAN errors. If you don’t get anything at all, the problem lies elsewhere, and I suggest you troubleshoot it one step at a time and possibly ask for help in another, more appropriate, forum (this is really not a support forum)

@ghost

I have changed the sensor and I am using LM35 Temperature Sensor now. I have connected the ‘Out’ Pin of sensor to Pin A0 of Wemos D1 R2 for Analog reading. Before doing this I tested the A0 pin with following piece of code:

long int reading = 0;
float avg = 0.0;
void setup()
{
    Serial.begin(9600);
}
void loop() 
{
    for(int i = 0; i < 10; i++)
    {
        reading += analogRead(A0);
        delay(50);
    }
    avg = reading/10.0; 
    reading = 0; 
    Serial.print("Average Count: ");
    Serial.print(avg);
    delay(1000);
}

This code works quite well for potentiometer with full reading range from 0 to 1024 for a 0-3.3 V range. The same code does not give count at all for LM35 which is already tested OK with Arduino Uno. I know that LM35 is having operating voltage range of 4-30 V and that is why I connected it to the 5 V pin of Wemos D1 R2 because it would not harm the Wemos as the analog voltage transduced from nearly 26 degree Celsius at my place, would not exceed 3.3 V level of Wemos. The count remains in between 0 and 5 as per the code. I have also tested the same sensor on fresh Wemos D1 R2 board where I observed the same issue. So I am reporting this bug of LM35 error with Wemos. Kindly help.

Shaunak Agastya Vyas

@robcazzaro

This is not a support forum, please ask your questions in the right forum (Wemos or ESP8266 Arduino

Closing this issue to avoid further unrelated questions

@ghost

The issue is not resolved yet. DHT22 Sensor is not working with Wemos for me even after trying all the solutions given here. The way I have described the issue with LM35 speaks that I am not just an another beginner. Now, please solve both the issues of DHT22 and LM35. I am not a rebellion, so please do not block me on GitHub. I am just an idiot who is stuck up and needs help badly.

Shaunak Agastya Vyas

@ghost
ghost

mentioned this issue

Nov 29, 2018

@khjoen

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

@j-opificius

My solution is to connect ground on DHT22 to GPIO0 which is held high at upload time.
AND in setup before initializing DHT22 three lines:

digitalWrite(0, LOW); // sets output to gnd
pinMode(0, OUTPUT); // switches power to DHT on
delay(1000); // delay necessary after power up for DHT to stabilize

This solution in conjunction with the two line fix to the library works for me so far, with a sample of one. My device is an ASAIR AM2302 hard wired onto a 3-pin adapter board with a 4k7 pull-up from data output to +ve and a cap across power.
It came up with no coaxing after a software upload for each of 10 attempts, and also after several simple power cycles (no upload) using a micro-USB source.
I’m going to build 8 units of this config, each powered from a 2 x AA 3V power source. I’ll report if there are any issues.

@yavimaya

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

That worked flawlessly on a ESP32 and dht22.
No errors at all.
Thank you!!

@teverth

In my case, I am using two DHT22 on an ESP32 and was getting lots of NAN readings like the others. I am using the currently published DHT22 library from the Adafruit website.
I tracked the issue down to checksum errors. And in fact, what it was is that from time to time the highest bit on the checksum transmitted by the DHT22 was not set to «1» when it had to. All other bits coming from the DHT22 matched what the checksum needed to be. So now I am masking the checksum check with 0x7F instead of 0xFF and presto: Not a single NAN result anymore.

Before that change, I also followed the recommendations above to comment out the two lines below and change the value to 50 in the last line of this part:

//digitalWrite(_pin, HIGH); 
//delayMicroseconds(40);  

// Now start reading the data line to get the value from the DHT sensor.
pinMode(_pin, INPUT_PULLUP);
delayMicroseconds(50);  // Delay a bit to let sensor pull data line low.

But these changes alone did not fix the checksum issue and are possibly not related in my case to the solution. But masking for 0x7F did the trick, see below.

DEBUG_PRINTLN(F(«Received:»));
DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(«, «));
DEBUG_PRINT(data[4] & 0x7F, HEX); DEBUG_PRINT(F(» =? «));
DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0x7F, HEX);

// Check we read 40 bits and that the checksum matches.
if ((data[4] & 0x7F) == ((data[0] + data[1] + data[2] + data[3]) & 0x7F)) {
_lastresult = true;
return _lastresult;
}
else {
DEBUG_PRINTLN(F(«Checksum failure!»));
_lastresult = false; // set to true to ignore checksum err
return _lastresult;
}

I also so other people posting their NAN issues and saw that they had the very same mismatch of the checksums, i.e.: Calculated checksum byte = 0xCA but received checksum byte = 4A, the high bit missing.
I think that perhaps the DHT22 signals something else with that top checksum bit that they don’t tell us in the datasheet? But ignoring that bit does no harm. The values that I get from my DHT22 sensors are all good and matching with independently measured values. So this fix sorted it all for me.

@DIYGuy01

did not help me. Still nan
ESP01 + AOSONG AM2302

But it works absolutely fine on Arduino Uno with the same lib

@khjoen

@DIYGuy01

I was trying 3 days to achieve working DHT22 AOSONG with ESP-01 without success, trying various libs, changes in them, power source, boards, sensors etc.
9 months ago I made sketch the same ESP-01 with ASAIR DHT22 and it was working fine until this moment when I recompiled and changed DHT22 sensor vendor (I think during this time libs also have changed).
New setup is working fine with Arduino Uno and Wemos D1 mini, but not with ESP-01. With debug on was getting constantly «DHT timeout waiting for start signal high pulse.»
Until I tried one trick which I found here on Github (do not remember where)
Simple:

Void setup() {  
// workaround for DHT22 due to NAN error
  digitalWrite(DHTPIN, LOW); // sets output to gnd
  pinMode(DHTPIN, OUTPUT); // switches power to DHT on
  delay(1000); // delay necessary after power up for DHT to stabilize
  dht.begin();
....

dhd.begin() should follow instantly. If you put it in pre setup section- won’t work.
It works 100% not missing any reading in my case also ESP-01 is used with deepsleep().

This workaround helped me. Not going to deep dive in libs, I’ve got working solution but I hope it will give you direction what is wrong with lib, timings or new generation of chinese sensors :)

@netixx

I have the ASAIR AM2302 (with shield and pull-up) and Wemos D1 mini (v3.0.0) and I can confirm @VikIborra suggestion to use D3 instead of the pre-wired D4 in the shield I received with it. I am using the latest v1.3.3 which has been published with fixes yesterday. With D4 I wasn’t able to read any data at all!

I am still getting a few NAN, every 15 measurement or so using the test sketch provided with the library.

@fabiom91

// digitalWrite(_pin, HIGH);
// delayMicroseconds(40);

Hi @robcazzaro I cannot find the two lines you quoted:

 // digitalWrite(_pin, HIGH);
 // delayMicroseconds(40);

In which file are them? .-.

@robcazzaro

This issue was opened on version 1.2.0 of the library, in 2017. The current version of the library has changed a lot, and according to the comments for release 1.3.2, the ESP8266 timing issues have been addressed. So probably nothing here applies anymore :)

@korovinn

Work for me.
Try to do these:

  1. Connect DHT22 «+» to D0 on esp8266 and NOT to 3,3v
  2. Connect DHT22 «out» to D3 on esp8266
  3. Use such code in void setup ()

void setup()
{
Serial.begin(115200);
pinMode(DHTPin, INPUT);
pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
dht.begin();
timer.setInterval(5000L, getdata);
}

@pentiumduck

Your code fixed this issue. Thank you !!!

@sheepsy90

That helped! Old lib works! It’s a start!

@fontanon

@robcazzaro and @everybody. Can someone test this https://github.com/khjoen/DHT-sensor-library with your respective boards and comment on your results.

The code is a bit more complicated than the original adafruit lib, but I think it complies to the datasheet of the DHT like sensors. I do use pullup resistor and it works at least on arduino uno and mega.

I do not own other boards so comments regarding results on them are welcomed.

For those interested in performance timings, there is that framework I put together: https://github.com/khjoen/perf-tester that uses the DHT lib as an example.

Happy testing.

Worked like a charm to me with Heltec WiFi LoRa 32 + DHT22 (AM23D2). I came from this tutorial: https://github.com/enzof6/arduino-lmic-for_ESP32 and end up with the NaN reading errors. Thanks for sharing.

fontanon

added a commit
to ttn-sevilla/arduino-lmic-for_ESP32
that referenced
this issue

Aug 1, 2020

@fontanon

@boumanb

Work for me.
Try to do these:

1. Connect DHT22 "+" to D0 on esp8266 and NOT to 3,3v

2. Connect DHT22 "out" to D3 on esp8266

3. Use such code in void setup ()

void setup()
{
Serial.begin(115200);
pinMode(DHTPin, INPUT);
pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
dht.begin();
timer.setInterval(5000L, getdata);
}

Thank you. Any explanation?

@GreaseMonkey88

I had the same problem using a DHT22/ESP8266(WemosD1Mini) for outdoor measurements connected to the 3.3V pin. After 24h or sometimes just hours I got NaN readings. So I sent the MCU to sleep for just 45s around every hour — that seems to work so far:

if (millis() >= 3600e3) // DeepSleep to "reset" the DHT22 sensor. Connect pins D0 + RST
  {
    ESP.deepSleep(45e6);
  }

Moderators: grovkillen, Stuntteam, TD-er

MonkeyTown

Normal user
Posts: 25
Joined: 08 May 2016, 02:29

DHT22 AM2302 — sensor stops working — NaN

#1

Post

by MonkeyTown » 27 May 2016, 01:01

I am using DHT22 ( wired version with the pull up resistor — AM2302) — https://www.adafruit.com/product/393

using two of them on two different boards:

Lolin — NodeMcu V3 with the NodeMcu Base Board — http://www.aliexpress.com/item/NodeMcu- … 29505.html
http://www.aliexpress.com/item/Free-Shi … 09072.html
Amica — http://www.aliexpress.com/item/Update-I … 64766.html

both connected using du-pont connectors, on GPIO13, all wired up properly, secured with hot glue.

The problem seems to be the same on both, happening on stable r_78, and 105 and 106.

Everything seems to work fine for a day, or several days and then suddenly I get a NaN (Not a Number) displayed on the little OLED and when looking at the web interface, serial stops reporting readings, just keep updating uptime.
One of the boards has BMP180 running alongside the DHT22, the other DS18b20 and they work just fine, even after dropping the DHT, they keep updating my domoticz server and thingspeak (so it’s not the server settings).
None of the board freeze, just drops the DHT22 but continues to work.

To get it working again:
— sometimes the web interface reboot feature is enough (that leads me to believe that it’s not a mechanical connection issue as I don’t even touch the board to reset it)
— sometimes I have to physically disconnect power to get the readings back

One board is powered by a dedicated 2A power supply, another directly from USB on my MB. No other issues, disconnects or whatnot….

I am not sure what else I can do to provide more info on this or how to debug further but will be very happy to try anything you guys would suggest, Thanks in advance (and in general for this awesome software!).


nightshark

Normal user
Posts: 25
Joined: 29 Apr 2016, 06:54

Re: DHT22 AM2302 — sensor stops working — NaN

#2

Post

by nightshark » 27 May 2016, 14:48

Mine does this too. It will eventually come back up. I’d like to know what others think.


MonkeyTown

Normal user
Posts: 25
Joined: 08 May 2016, 02:29

Re: DHT22 AM2302 — sensor stops working — NaN

#3

Post

by MonkeyTown » 28 May 2016, 01:06

nightshark wrote:Mine does this too. It will eventually come back up. I’d like to know what others think.

Thanks. At least I know I’m not the only one.
It sometimes does come back, 20 min later, but sometimes 8 hours later still NaN.. This makes it useless, AFAIK. I might switch to BMP280 in the meantime… But I would love to see this fixed as I am quite fond of the AM2302/DHT…


MonkeyTown

Normal user
Posts: 25
Joined: 08 May 2016, 02:29

Re: DHT22 AM2302 — sensor stops working — NaN

#4

Post

by MonkeyTown » 06 Jun 2016, 05:46

Any updates? Anyone?

Is there any chance that the am2302 has a pull-up resistor already in place? People using the DHT22 on RasPi with 3.3V recommend not using one. I have a DHT22 in another project so I want to pull it out and use without the resistor.
I have had my last two NaN failures only remedied after disconnecting 3.3V and GND of the sensor so this really sucks as the AM2302 has been my sensor of choice with Arduinos, always performing great…

Can anyone help in fixing this? I’ll report back after my trial without the resistor.


pbertra

Normal user
Posts: 8
Joined: 30 May 2016, 12:19

Re: DHT22 AM2302 — sensor stops working — NaN

#5

Post

by pbertra » 06 Jun 2016, 10:21

I also have the issue with nodeMCU v2 and am2301 but mine is battery powered… And I guess the issue is coming from there as the minimum voltage is 3.3v.

What is noticed is that the nodemcu board can continue working and sending data when the battery voltage gets lower but the am2301 doesn’t work anymore. And the voltage drops quite quickly below 3.3V because the AM1117 regulator (and potentially a diode I think) imply a voltage drop of nearly 1V!


Drum

Normal user
Posts: 300
Joined: 07 Feb 2016, 11:56

Re: DHT22 AM2302 — sensor stops working — NaN

#6

Post

by Drum » 06 Jun 2016, 17:05

I have had this happen on a NodeMCU V2 as well, but I think after I fried the diode on the power input and replaced it with a piece of wire, this stopped happening. There is a Power section in the wiki which explains how this can be a problem. The DHT-22 specsheet says 3.3 to 6 V and if there is a diode on the input of the AMS1117 It may not be getting 3.3V.

I also have 2 Olimex MOD-WIFI-ESP8266-DEV boards with DHT-22, and DS18B20 on 2 AA NiMh batteries, a Solar cell and LM3671 to keep the power at 3.3V. Both have been running since February with no problems. Right now I am only using LM3671 or MCP1826 to regulate the power. The AMS1117 I could get had too much overhead and batteries just didn’t last very long. They must be cheap, no idea.

I am not a big fan of the AMS1117, but it probably works okay, I just haven’t had a lot of success with them. I also don’t think NodeMcu’s work really well on batteries, but not being an EE, I won’t argue that. On my NodeMCU V2 I have a DHT-22, DS18b20, LCD display (5V) with a level shifter and button to turn th e light on, and a couple of good size Capacitors. Of course also no diode, and a 2A USB power supply. The only problems I have had are related to the whole thing currently being on a cheap breadboard, breathe om it and ikt resets, but stay away and it can run for weeks with no problems. I am working on a hardwired system, but that takes a lot more time to build.


Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 0 guests

I am new to electronics and microcontrollers and hope this is the right spot on StackExchange. I have been playing around with an Arduino Micro, connecting different sensors and a display and display data.

I just bought a NodeMCU so I can send sensor values to a database using a DHT22. This is the first test, other sensors will follow.

I am using Arduino Studio with the board configuration for this device.

Everything works fine, Wifi, Serial, but I only get bad readings from the sensor.

  • I checked 2 DHT22 with my Arduino, they work.
  • I read that the Arduino has integrated pull-ups and a ESP8266 might not have them, so I added 4.7k and 10k between data and 3.3V. But I am not entirely sure about this.
  • The DHT22 is using 3.3V on the NodeMCU and the Arduino. Not 5V. -> Arduino works.
  • I tried different D pins
  • I tried removing or adding code lines like dht.begin, pinMode, etc.
  • I used the DHTtest example which also gets bad readings.
  • I found other projects — Weather monitoring — which showed their wiring. Some of them also did not use a pull-up resistor. I also tried it without.
  • Wiring checked multiple times -> I hope I’m not blind right now.
  • Measured the resistors i added -> ok
  • Measured the voltage between GND and 3.3V -> ok
  • I don’t have an oscilloscope (yet) so I don’t know whats on the data line.

So I am doing something wrong here but I can’t figure out what.

Thanks for help. Very much appreciated.

Понравилась статья? Поделить с друзьями:
  • Df624 ошибка рено меган 2 как лечить
  • Diag 03501 03 ошибка ман
  • Diablo 3 ошибка d3d как исправить
  • Df480 ошибка рено
  • Diablo 3 ошибка 3006 что делать