Giter Site home page Giter Site logo

dhtnew's Introduction

Arduino CI Arduino-lint JSON check GitHub issues

License: MIT GitHub release PlatformIO Registry

DHTNew

Arduino library for DHT11 and DHT22 (and compatible) with automatic sensor type recognition.

Description

DHTNEW is stable for both ARM and AVR. It is based upon the well tested DHTlib code. This is the main development library of all my DHT libraries.

Supports DHT11, DHT22, DHT33, DHT44, AM2301, AM2302, AM2303 as these all have the same protocol. Note there are differences e.g. DHT11 has no negative temperature, no decimals, and a longer wakeup time.

The DHTNew library returns Temperature in degrees Celsius and Humidity in 0.0 - 100.0 %RH. For converting temperature to Fahrenheit or Kelvin, see https://github.com/RobTillaart/Temperature.

Sonoff Si7021

Since 0.4.14 there is experimental support for the Sonoff Si7021. No hardware yet to test this myself, but it is confirmed to work. See #79. Seems the Sonoff Si7021 sensor is very sensitive in the wakeup timing. This behaviour needs to be investigated in the future.

To use the library one should call setType(70).

Feedback (both positive and negative) about the Sonoff Si7021 sensors is welcome.

AM2320, AM2321 and AM2322

Since 0.4.18 there is experimental support for the AM2320, AM2321 and AM2322. Not tested myself, but AM2320 is confirmed to work, see RobTillaart/AM232X#26 As the AM2321 and AM2322 are quite identical according to the datasheet, those are expected to work too.

To use the library one should call setType(22) as the protocol is identical to the DHT22. If there are differences in operation type (23) will be elaborated. The value 23 is now mapped upon 22 code.

Feedback (both positive and negative) about the AM232X sensors is welcome.

Note: check the datasheet how to connect!

Related

DHT PIN layout from left to right

Front Description
pin 1 VCC
pin 2 DATA
pin 3 Not Connected
pin 4 GND

Note: check the datasheet how to connect!

Specification DHT22

Model DHT22 Notes
Power supply 3.3 - 6.0 V DC
Output signal digital signal via single-bus
Sensing element polymer capacitor
Operating range humidity 0.0-100.0% RH temperature -40° - 80° Celsius
Accuracy humidity ±2% RH(Max ±5% RH) temperature < ±0.5° Celsius
Resolution or sensitivity humidity 0.1% RH temperature 0.1° Celsius
Repeatability humidity ±1.0% RH temperature ±0.2° Celsius
Humidity hysteresis ±0.3% RH
Long-term Stability ±0.5% RH/year
Sensing period average: 2 s
Interchangeability fully interchangeable
Dimensions small 14 x 18 x 5.5 mm big 22 x 28 x 5 mm

Interface

#include "dhtnew.h"

Constructor

  • DHTNEW(uint8_t pin) defines the dataPin of the sensor.
  • void reset() might help to reset a sensor behaving badly. It does reset the library settings to default, however it does not reset the sensor in a hardware way.
  • uint8_t getType() 0 = unknown, 11 or 22. In case of 0, getType() will try to determine type. Since 0.4.14 type 70 is added for experimental Sonoff Si7021 support.
  • void setType(uint8_t type = 0) allows to force the type of the sensor.
Type Sensors Notes
0 not defined
11 DHT11
22 DHT22 a.o most others
23 DHT22 a.o mapped to 22 for now
70 Sonoff Si7021 experimental
other sets to 0 0.4.20

Base interface

  • int read() reads a new temperature (Celsius) and humidity (%RH) from the sensor.
  • uint32_t lastRead() returns milliseconds since last read()
  • float getHumidity() returns last read humidity = 0.0 - 100.0 %RH. In case of an error it returns DHTLIB_INVALID_VALUE == -999. Note this error value can be suppressed by setSuppressError(bool).
  • float getTemperature() returns last read temperature in Celsius. Range depends on the sensor. In case of an error it returns DHTLIB_INVALID_VALUE == -999. Note this error value can be suppressed by setSuppressError(bool).

Offset

Adding offsets works well in normal range however they might introduce under- or overflow at the ends of the sensor range. Humidity is in % RH. Humidity is constrained to 0.0 - 100.0 % in the code. Temperature is in degrees Celsius. For temperature such constrain would be type dependant, so it is not done.

  • void setHumOffset(float offset) typical < ±5% RH.
  • void setTempOffset(float offset) typical < ±2°C.
  • float getHumOffset() idem.
  • float getTempOffset() idem.

Control

Functions to adjust the communication with the sensor.

  • void setDisableIRQ(bool b ) allows or suppresses interrupts during core read function to keep timing as correct as possible. Note AVR + MKR1010
  • bool getDisableIRQ() returns the above setting. Default true.
  • void setWaitForReading(bool b ) flag to enforce a blocking wait.
  • bool getWaitForReading() returns the above setting.
  • void setReadDelay(uint16_t rd = 0) To tune the time it waits before actual read. This reduces the blocking time. Default depends on type. 1000 ms (dht11) or 2000 ms (dht22). set readDelay to 0 will reset to datasheet values AFTER a call to read().
  • uint16_t getReadDelay() returns the above setting.
  • void powerDown() pulls dataPin down to reduce power consumption
  • void powerUp() restarts the sensor, note one must wait up to two seconds.
  • void setSuppressError(bool b) suppress error values of -999 => You need to check the return value of read() instead.
    This is used to keep spikes out of your plotter / graphs / logs.
  • bool getSuppressError() returns the above setting.

Operation

See examples

TIME_OUT

If consistent TIMOUT_C or TIMEOUT_D occur during reading a sensor, one could try if allowing interrupts solves the issue DHT.setDisableIRQ(false).

This solved this problem at least on

  • AVR boards - is build into the constructor
  • MKR1010 Wifi - see #67 (added as comment in the examples)

In version 0.4.10 the TIMEOUT_C is extended from 70-90 us to even suppress the TIMEOUT_C even more. See discussion and tests in #67.

Serial

The MKR1010Wifi board need to wait for Serial at startup if you want to monitor it from the IDE. Adding the line while(!Serial): fixes this. (added to the examples).

There might be more boards that need this line to work properly.

DHT22 and ESP8266

  • The DHT22 sensor has some problems in combination with specific pins of the ESP8266. See more details

Voltage AM2301 and ESP8266

In a test an AM2301 had problems giving no humidity (99.9% overflow) when the DHTStable library was used with an ESP8266. (Reported by mail, no GH issue). As this DHTStable library is strongly related to the DHTNew it is mentioned here too.

After days of testing and thinking and more testing the cause was found. The AM2301 was powered by a 5V3 power supply which was apparently too high while having the data handshakes at 3V3. When the VCC voltage was lowered to 5V1 it appeared to work as it should. (Kudos to Viktor for finding the cause)

History

DHTNEW has some new features compared to the DHTlib code.

  1. The constructor has a pin number, so the one sensor - one object paradigm is chosen. So you can now make a DHTNEW object bathroom(4), kitchen(3), etc.
  2. The read() function now reads both DHT11 and DHT22 sensors and selects the right math per sensor based upon the bit patterns.
  3. An offset can be set for both temperature and humidity to have a first-order linear calibration in the class itself. Of course, this introduces a possible risk of under- or overflow. For a more elaborated or non-linear offset, I refer to my multimap class.
  4. lastRead() keeps track of the last time the sensor is read. If this is not too long ago one can decide not to read the sensors but use the current values for temperature and humidity. This saves up to 20+ milliseconds for a DHT11 or 5+ milliseconds for a DHT22. Note that these sensors should have 1-2 seconds between reads according to specification. In the future, this functionality could be inside the library by setting a time threshold (e.g. 1 second by default) to give more stable results.
  5. Added interrupt enable/disable flag to prevent interrupts disturb timing of DHT protocol. Be aware that this may affect other parts of your application.
  6. (0.1.7) added an automatic check of lastRead in the read call. If request a read to fast it will just return OK.
  7. (0.1.7) added waitForReading flag (kudos to Mr-HaleYa) to let the sensor explicitly wait until a new value can be read.
  8. (0.2.0) Temperature and humidity are private now, use getTemperature() and getHumidity()
  9. (0.2.1) Adjusted the bit timing threshold to work around issue #11
  10. (0.2.2) added ERROR_SENSOR_NOT_READY and differentiated timeout errors.
  11. (0.3.0) removed interrupt flag, now the library always disables interrupts during the clocking of the bits. Added getReadDelay & setReadDelay to tune reading interval. Check the example code. Adjusted the timing in the wake-up part of the protocol. Added more comments to describe the protocol.
  12. (0.3.1) added powerDown() and powerUp() for low power applications. Note that after powerUp() the user must wait for two seconds before doing a read(). Just like after a (re)boot.
    Note: The lib does not (yet) control the power pin of the sensor. Discussion see #13
  13. (0.3.2) Added setSuppressError() and getSuppressError() so the library will not output -999 but the last known valid value for temperature and humidity. This flag is useful to suppress 'negative spikes' in graphs or logs. Default the error values are not suppressed to be backwards compatible.
    Added #ifndef around DHTLIB_INVALID_VALUE so the default -999 can be overruled compile time to set another error value e.g. -127 or -1 whatever suits the project.
  14. (0.3.3) Refactored the low level readSensor() as the BIT SHIFT ERROR issue #29 and issue #11 popped up again. It was reproduced "efficiently" with an ESP32 and by using long wires. Fixed with an explicit digitalWrite(dataPin, HIGH) + delayMicroseconds() to have enough time between pulling the line HIGH and polling for the line LOW.
  15. (0.3.4) Added waitFor(state, timeout) to more precisely follow the datasheet in terms of timing. Reintroduced the interrupt enable/disable flag as forced noInterrupts() could break the timing of the DHT protocol / micros() - seen on AVR.
  16. (0.4.0) Added DHTLIB_WAITING_FOR_READ as return value of read => minor break of interface
  17. (0.4.1) Added Arduino-CI support + gettype() now tries to determine type if not known.
  18. (0.4.2) Fix negative temperatures. Tested with DHTNew_debug.ino and hex dump in .cpp and a freezer.
    Note: testing in a freezer is not so good for humidity readings.
  19. (0.4.3) Added reset() to reset internal variables when a sensor blocks this might help. Added lastRead() to return time the sensor is last read. (in milliseconds).
  20. (0.4.4) DO NOT USE incorrect negative temp.
  21. (0.4.5) Prevent -0.0 when negative temp is 0; DO NOT USE as it maps every negative temp to zero.
  22. (0.4.6) Fixed negative temperature (again).
  23. (0.4.7) fix #60 negative temperatures below -25.5°C + readme.md.
  24. (0.4.8) fixes to improve Arduino-lint.
  25. (0.4.9) add optional flag DHTLIB_VALUE_OUT_OF_RANGE.
  26. (0.4.10) updated build-CI to do compile test - UNO, due, zero, Leonardo, m4, esp32, esp8266, mega2560. updated readme.md - added badges and remarks after testing with MKR1010 Wifi. updated TIMEOUT_C from 70 -> 90 us to minimize its occurrence - See #67. added while(!Serial); in examples to they work for MKR1010 Wifi.
  27. (0.4.11) update library.json, license, minor edits (cleanup), unit tests
  28. (0.4.12) Fix #72, delayMicroseconds() for wakeUp
  29. (0.4.13) Fix #76, disable interrupts for ESP32.
  30. (0.4.14) added experimental support for Si7021.
  31. (0.4.15) Fix #81, recognize DHT22 as type 70. Add minimal wakeup delay.
  32. (0.4.16) Fix #84 correct the reading of type 70 for Sonoff Si7021.
  33. (0.4.17) fix #86, define constants explicit as float.
  34. (0.4.18) Update readme.md and library.* about support for AM2320/21/22.
  35. (0.4.19) Update readme.md
  36. (0.4.20) Update GitHub actions and readme.md

Future

Must

  • update documentation

Should

  • test on more boards
  • #if defined(MKR1010) // TODO find out real define #67
    #ifdef ARDUINO_SAMD_MKRWIFI1010
    #error found
    #endif

Could

  • test compatibility => table.
  • investigate temperature constraining (type dependant)
if (type == 11) temp = constrain(temp,   0, 100);
if (type == 22) temp = constrain(temp, -40,  80);
etc.

Wont

  • move all code from .h to .cpp

Support

If you appreciate my libraries, you can support the development and maintenance. Improve the quality of the libraries by providing issues and Pull Requests, or donate through PayPal or GitHub sponsors.

Thank you,

dhtnew's People

Contributors

argltuc avatar budulinek avatar mr-haleya avatar pascalcorpsman avatar robtillaart avatar startercraft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

dhtnew's Issues

replace internal storage float with int

To save some RAM the internal storage in the class can be optimized:
int for T & H
byte for offset (assuming it is never more than +- 12.7 which is quite a bit.

flloat math will move from the read() function to the getTemp() function.
So expect that to be about equal.

read DHT11 with 3V3 logic/1Mhz

Is it possible to somehow read a DHT11 with an ATMEGA328P running at 1 MHz? The reason the CPU is running so slow is because this is a battery operated project, thus I am trying to bring down current consumption to as low as possible. I tried using the minimum example and naturally received -999. I realize that the sensor is running too fast for the CPU at this rate, but is there some kind of trick to nevertheless capture the sensor readings?

Example needed for waitForRead flag

version 0.1.7 supports a waitForRead flag, however an example showing its use is missing at the moment. The example should show the use and the added value of the flag. If needed a readme.md file to explain the example should be added.

setTempOffset and setHumOffset

It looks like the header has definitions for setTempOffset/getTempOffset and setHumOffset/getHumOffset and the class has the variables, but it doesn't seem that the implementation is missing.

Parallel processing of multiple Sensors

Hi Rob,

Thanks for keeping active on this DHTNew Library you are making some great improvements!

I recently applied the non-blocking approach to read a DHT Sensor on a device that had many other tasks as well. It works very well and is very useful in that project as the device also functions as a HTTP Server and I don't want to block request etc.

However that device only has 1 DHT Sensor. I have other devices that have 4 or 5 DHT Sensors and I would like to process the DHT readings as soon as possible to achieve a high frequency of readings.

I used to poll the DHT sequently waiting on each on to get stable, do the reading and then move on to the next one etc. It works OK but is a bit slower then I would like...

So I did an experiment with use an ESP D1_Mini board with 3 DHT22 sensors.
Using the latest version of your lib: robtillaart/DHTNEW@^0.4.18

The code creates 3 Sensor objects and starts a new read on each using the non-blocking approach.
Then in the main loop I poll each and read the temp when ready.

Its seems to work OK but I am a bit suspicious that all 3 always finish at the same time and I do get slightly different readings as expected because of the accuracy of the sensor (at least that seems to suggest that each sensor state is handled separately).

If I completely disconnect each sensor it also seems to work as expected I only when I reconnect it it finishes the polling for that sensor...

It is really that I don't trust them finishing always at the same time I worry about some static variabel in your lib that is not instance based if you know what I mean (I know I am using Java terminology but tat is the only way I can explain it)

So basically I am asking your opinion as the developer of this lib whether you think parallel sensor reading should be feasible or not. ANd if so maybe you can explain why they always finish at the exact same iteration unless fully disconnected...

Correction: In my latest test I reduced the poll delay to 10 ms and now 1 sensor was ready 1 iteration before the others 2 so maybe it is all OK... Still interested in your opinion though!

I Attached my test code and sample output...

Many thanks,

Toine

experiment.zip

pin setting at runtime

Hi,
I am looking for a library with the possibility to define the pin at runtime.
It is possibile with this one?
Thanks

Warning! Ignoring broken library manifest

I get a warning about a broken manifest when importing your library in PlatformIO. I think this is also the reason why I was not able to install it globally but had to reference the git repository as lib_deps in the platformio.ini file.

Not sure if this a related directly to your lib or to some PIO meta data service.

Processing attiny84 (platform: atmelavr; board: attiny84; framework: arduino)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/attiny84.html
PLATFORM: Atmel AVR 2.1.0 > Generic ATtiny84
HARDWARE: ATTINY84 8MHz, 512B RAM, 8KB Flash
DEBUG: Current (simavr) On-board (simavr)
PACKAGES: 
 - framework-arduino-avr-attiny 1.3.2 
 - toolchain-atmelavr 1.50400.190710 (5.4.0)
LDF: Library Dependency Finder -> http://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Warning! Ignoring broken library manifest in /home/me/share/Source/microcontroller/PlatformIO/Oled/.pio/libdeps/attiny84/DHTNew
Warning! Ignoring broken library manifest in /home/me/share/Source/microcontroller/PlatformIO/Oled/.pio/libdeps/attiny84/DHTNew@src-bcd93bb4e455076ee41a862dc09b6fe3
Found 20 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <DHTNew@src-bcd93bb4e455076ee41a862dc09b6fe3> #9b54ff1
|-- <Tiny4kOLED> 1.5.1 #7dbddb2
|   |-- <TinyWireM> 1.0.1
|   |-- <Wire> 1.0
Building in release mode

Compiler warning, conversion float to double

Hello there,

Compiling with extra warning flags I've noticed an annoying warning (that even brakes compilation if -Werror).

.....\libraries\DHTNEW\dhtnew.cpp: In member function 'int DHTNEW::_read()':
.....\libraries\DHTNEW\dhtnew.cpp:243:18: warning: implicit conversion from 'float' to 'double' to match other operand of binary expression [-Wdouble-promotion]
if (_humOffset != 0.0)
~~~~~~~~~~~^~~~~~
.....\libraries\DHTNEW\dhtnew.cpp:249:19: warning: implicit conversion from 'float' to 'double' to match other operand of binary expression [-Wdouble-promotion]
if (_tempOffset != 0.0)
~~~~~~~~~~~~^~~~~~

Comparing against '(float)0.0' instead of '0.0' should clear that warning.

Thanks

Problem: wrong values at negative temperatures an ESP8266 and DHT22

I use the DHT22 in combination with an ESP8266 and this lib.
When having negative temperatures, the resulting value of getTemperature() is -3278.6 at -0.1°C
To fix negatives values a recalculation is nessecary:

#include <stdint.h>
if(temperature < 0)
 {
   temperature = (temperature = (INT16_MAX - temperature*-10)*-0.1; - temperature*-10)*-0.1;
 }

This was tested with Arduino IDE against lib version 0.4.3, installed via Arduino library manager.

Question about Float

Hey Rob,
Didn't you say that one of the DHTs gave a .1 number but you had float disable to save space or something like that? I don't know if that made any sense. Basically I wanted to know if the library can (or has any plans to) give float values back (or make that an option like another flag?) My temp is borderline 23-24°C so it bounces between these two like crazy on my graphs so I was checking to see if decimals where an option as a reply from the sensors.

Sonoff Si7021 gives wrong temperature and humidity

Hi Rob, I was away for the weekend.
You made the changes very quickly :-)
I can't test it today but y see line #183
if (_type == 22) // DHT22, DHT33, DHT44, compatible
should be
if ((_type == 22) || (_type == 70)) // DHT22, DHT33, DHT44, compatible

otherwise we get wrong readings

best regards

Originally posted by @phiguimaran in #79 (comment)

Test sketch

Do you happen to have a test sketch to try? Arduino Esp32

"Sensor not ready," meaning

Hi, I've been trying to get readings from a DHT11 sensor using the DHTNew library and am consistently running into a problem.

When trying the sketch dhtnew_test, the 0.2.0 version returns "Timeout_error", and the version 0.3.3 returns "Sensor not ready," from what I understood this means the sensor does not return fast enough for the code to get readings. I've used a 5.1k Ohms pull-up resistor (as the datasheet recommends), as the cables are less than 20 meters long (just a few cm long in fact). I've tried using both an analog and digital pin, the results are the same. The sensor is lit red though, so I assume it is correctly powered and grounded.

I don't know what may be going wrong or how to interpret this returned error, should I try to modify the code or is the problem coming from the connections ?

Request about DHTnew

Hello Rob,

I'm using your DHT library DHT new, and it's working really well;

But I'm trying to declare a table of DHTnew sondes (because I have a lot of sondes, and it will really simplify my code).

Could you tell me, if it will be possible for you to make an evolution in this library in order to be able to declare a table of sondes?
Something like DHTNEW MyProbe[8];
Then to declare the pins with a function call?

error reading am2302 over longer wire

When using longer wire for am2302 (like 1-5m) there is always error on read. Checked with oscilloscope - the signal looks fine. Grove_Temperature_And_Humidity_Sensor library had no problem with the same hardware setup.
I've used ESP32 DevKit V1.

Fix negative temperature below -25.5°C

As the DHT has an operational range from -40°C (-40°F) it fails for the lowest temperatures.

Bug is in
line 202

      if(_bits[2] == 0x80)
      {
        _temperature = -_temperature;
      }

works well down to -25.5 C but not below that, as the _bits[2] will be 0x81 for such low temperatures.
For most applications this is not an issue, but it is still a bug.

Code proposal

      if(_bits[2] & 0x80  != 0)
      {
        _temperature = -_temperature;
      }

Unfortunately I cannot test down to -40°C (my fridge goes to -20 or so)

Remove humidity and temperature as public members.

As this is a breaking change it should be in a separate release 0.2.0

work done so far:

  1. added function getHumidity()
  2. added function getTemperature()
  3. updated all examples to the new interface version

Support for SonOff Si7021

Hello! Thanks for nice library. Is the any plans on support for Sonoff Si7021 sensor which is slightly different from Sonoff am2301?

AM2322 Humidity 99.9 Temp OK

Hi;

Am testing this lib on the AM2322, I have a bunch of them and are testing on 2 of them, both give same results.

I have tried different pins (ESP32) but the results are the same on both devices and different pins.

Temperature reading is good, but humidity is always 99.9, if I introduce a negative offset then the values will always be 99.9 - that offset.

Have tried defining type as 22 or not defining type, result is the same, have also tried slowing down the reads to 5 seconds but no difference.

Humidity shown on other devices is around 75% currently.

It works with different lib on I2C but I am desperately short on pins :-)

EDIT

Just added a 4K7 resistor to pullup the data line, no difference.

07:45:01.770 -> BEFORE OFFSET
07:45:06.778 -> 	29.2
07:45:06.975 -> 99.9
07:45:06.975 -> AFTER -10 HUMID OFFSET
07:45:09.081 -> 89.9	29.2
07:45:11.186 -> 89.9	29.2
07:45:13.293 -> 89.9	29.2
07:45:15.397 -> 89.9	29.2
07:45:17.505 -> 89.9	29.2

Any suggestions ?

Si7021 by Sonoff

Hi, I'm usinng your library in various proyects, it's great !!
I'm trying to use it with the sensor that's came with Sonoff TH.
It's a board that include Si7021 sensor and some circuits to comunicate with 1 wire.
To make this work I have to change the wakeup delay to a value near 500 microseconds
If I coment lines :
do { // HANDLE PENDING IRQ yield(); // 180 gives good wakeup delay on UNO for DHT22 / DHT11 (issue #72) delayMicroseconds(180UL); } while((micros() - startWakeup) < (_wakeupDelay * 1100UL));
and change for delayMicroseconds(500UL); its work well.

I wonder if there is a way to configure this without having to edit the library?

Thanks in advance

error yield() no se declaró

(spanish)

i tried to use the library and i get this error:

the code:

#include <dhtnew.h>

void setup(){
  
}
void loop(){
  
}

compiler:

/home/germe/Documentos/arduino/libraries/DHTNEW042/dhtnew.cpp:112:13: error: ‘yield’ no se declaró en este ámbito
       yield();
             ^
/home/germe/Documentos/arduino/libraries/DHTNEW042/dhtnew.cpp: En la función miembro ‘int DHTNEW::_readSensor()’:
/home/germe/Documentos/arduino/libraries/DHTNEW042/dhtnew.cpp:248:9: error: ‘yield’ no se declaró en este ámbito
   yield();
         ^

the compiler is in spanish because my system is in spanish. it say "error in the member function ‘int DHTNEW::_readSensor()’:
yield not declared in this ambit
sorry for my english, i speak spanish

my library version is:0.4.2
i'm on arduino ide 2:1.0.5+dfsg2-4.1
the error ocurrs when i import the library. if i put more code the error splashes too

Adding name tag to sensor

An descriptive name into the sensor so I can set

DHTNEW s(4);
kitchen.setName("kitchen");   // or PROGMEM ?
...
Serial.println( s.name);

an 8 byte string or progmem would make loops over multiple sensors easier (no parallel array of strings).

Drawback memory usage.

Sensors getting stuck at a certain value

I have two AM2302s connected to pins 0 and 2 of an ESP32, after a while of working perfectly they only return a static value...

My loop looks like this:

  1. AM2302s get read using .read();
  2. Values get sent to InfluxDB using .getTemperature(); and .getHumidity();
  3. 10 second wait

I have tried adding .reset(); before the 10 second wait but that only made them return 0 or -999 instead of a static value.
chrome_9umnscGanw

read() hangs with MkrWiFi + MkrConnector Board

I have 6 DHT22 sensor connected to a WifiMkr1010 Board (sensors connected via a MKR Connector Carrier board on D0-D5)
Until recently I used DHTStable library (1.0.1) which worked fine but I ran onto a bug when outdoor temp dropped below 0c.

So I changed over to DHTNew (0.4.9) but unfortunaly it doesn't seem to work in combination with this board. I have another set of sensors on an ESP8266 (wemos Mini) board and they word firn with the DHTNew library.

On the MKR1010 it seems to hang on the read() method.
if I precede .read() with .setType(22) it does continue but reports unknown error -5 on the first attempt followed by unknown error -8 on subsequent attempts.

I have attached my sourcecode at the top you'll see do defined statement to enable DHTNEW and a basic debug option...

Any idea what could be wrong any suggestion to troubleshoot?

Thanks
main.zip
!

Need for calibrateReadDelay()

During the investigations of issue #11 it became clear that the READ_DELAY of 2250 or 2000 datasheet is way higher than needed. It is a good default but power users might want to read the sensor more often. The library blocks this if the last read is less than READ_DELAY ago. This should stay for the normal usage.

For the power users a function uint16_t optimizeReadDelay() (name?) could find the optimal timing of an individual sensor and adjust READ_DELAY (including a safety margin of e.g. 100 ms of course). The adaptive delay example gives some ideas how to do this. The function should return the value found.

Also a resetReadDelay() should be available?

general questions

I would like to work on and improve this because I want to use it so I want to assure it is reliable.
I would like to use a DHT22 but I'm starting with a DHT11 since currently, that's all I have.

When defining a type getType(); in the .h does not seem to do anything or refer to any functions. did you remove this? and if so how can a type be defined? will it still work with the 22 33 since it appears there is no way to define the type and it defaults to 11 12

You have the humidity readings floated but all humidity reading outputs are never decimals. Is this intentional?

In your examples, you call mySensor.humidity but the humidity should be private and instead, mySensor.getHumidity() should be called. same goes for temperature

I am just curious and have nothing to do during this "lockdown" and am offering to help if there is any way to do so.

  • Regards Hale

ESP32 error

Dear Rob, first of all thank you very much for this wonderfull and working library!
I was just testing your library on a ESP32 and from time to time a got the error -4 DHTLIB_ERROR_SENSOR_NOT_READY
I checked all the signal with an oscilloscope and I couldn't find any faults on the signal.
After searching a while on the web I found that the instruction " noInterrupts();" would probably not be implemented on an ESP32.
So I gave it a try and inserted additionally the following command:

#if defined(ESP32)  
  if (_disableIRQ) { portDISABLE_INTERRUPTS();}
#endif

and later to allow again interrupts:

#if defined(ESP32)
  portENABLE_INTERRUPTS();
#endif

Since then I didn't get any more errors. I hope this helps somehow.

Ticker compatibility

Wemos D1R2 - ver. 0.4.17
The Library doesn't work if used within a function called by a Ticker, the board generates an exception and restarts.
Output:
`dhtnew_test.ino
LIBRARY VERSION: 0.4.17

  1. Type detection test, first run might take longer to determine type
    STAT HUMI TEMP TIME TYPE
    OK, 77.5, 19.7, 5270, 22

User exception (panic/abort/assert)
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Panic core_esp8266_main.cpp:137 __yield

stack>>>
(((((cut)))))`

Code:

#include <Ticker.h>
#include <dhtnew.h>

Ticker tckRead;
DHTNEW mySensor(D5); // ESP 16    UNO 5    MKR1010 5

void setup()
{
  Serial.begin(115200);
  delay(5000);
  Serial.println("dhtnew_test.ino");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHTNEW_LIB_VERSION);
  Serial.println();

  Serial.println("\n1. Type detection test, first run might take longer to determine type");
  Serial.println("STAT\tHUMI\tTEMP\tTIME\tTYPE");
  test();
  delay(1000);
  tckRead.attach(3.0, test);
} // setup

//
void loop()
{
  delay(1);
} // loop

//
void test()
{
  // READ DATA
  uint32_t start = micros();
  int chk = mySensor.read();
  uint32_t stop = micros();

  switch (chk)
  {
  case DHTLIB_OK:
    Serial.print("OK,\t");
    break;
  case DHTLIB_ERROR_CHECKSUM:
    Serial.print("Checksum error,\t");
    break;
  case DHTLIB_ERROR_TIMEOUT_A:
    Serial.print("Time out A error,\t");
    break;
  case DHTLIB_ERROR_TIMEOUT_B:
    Serial.print("Time out B error,\t");
    break;
  case DHTLIB_ERROR_TIMEOUT_C:
    Serial.print("Time out C error,\t");
    break;
  case DHTLIB_ERROR_TIMEOUT_D:
    Serial.print("Time out D error,\t");
    break;
  case DHTLIB_ERROR_SENSOR_NOT_READY:
    Serial.print("Sensor not ready,\t");
    break;
  case DHTLIB_ERROR_BIT_SHIFT:
    Serial.print("Bit shift error,\t");
    break;
  case DHTLIB_WAITING_FOR_READ:
    Serial.print("Waiting for read,\t");
    break;
  default:
    Serial.print("Unknown: ");
    Serial.print(chk);
    Serial.print(",\t");
    break;
  }
  // DISPLAY DATA
  Serial.print(mySensor.getHumidity(), 1);
  Serial.print(",\t");
  Serial.print(mySensor.getTemperature(), 1);
  Serial.print(",\t");
  uint32_t duration = stop - start;
  Serial.print(duration);
  Serial.print(",\t");
  Serial.println(mySensor.getType());
  // delay(2500);
} // test

// -- END OF FILE --

(updated code tags for syntax highlight)

Add enable / disable power supply pin

To support low power usage e.g. when batteries power the sensor, one need to be able to switch of the power supply of the DHT sensor.

This would imply an additional power pin in the constructor.
This power pin has a default of 0xFF that states ==>no power pin.

DHT(datapin, powerPin = 0xFF);

void DHT.enable()
{
  if (_powerPin == 0xFF) return;
  digitalWrite(_powerPin , HIGH):
}

void DHT.disable()
{
  if (_powerPin == 0xFF) return;
  digitalWrite(_powerPin , LOW):
}

bool DHT.sensorEnabled()
{
  return (_powerPin != 0xFF);
}

uint8_t  _powerPin ;

investigate
depending on the processor it can or cannot deliver the power from an IO pin directly.
Working with an extra mosfet is always possible

investigate
After startup a delay is needed. Put this in the library or is the user responsible?

Small documentation improvement: add unity

Hello,

A small suggestion to improve documentation: explicit unity :

Document getHumidity() return a value between 0.0-1.0 or between 0.0-100.0, to be interpreted as a percent of humidity.

float getTemperature() returns temperature as °C or °F ?

Thanks

Thoughts about setting Humidity & Temperature to -999

These thoughts are triggered by issue #11 (burst of failures with DHT22 + ESP32)

Current behavior
In case of an error the T&H is set to -999. This value is artificial, out of physical range and chosen to trigger the user reading the sensor went wrong. This is double as the read() provides a return value indicating OK or ERROR.

Proposed behavior
Alternative one should not setting this -999 value as the failed read might depending on the cause still have acceptable H&T value in some cases. Depending on return value:

  • if OK -> set new values (default, as is)
  • if CHECKSUM error -> set new values, as these might be right (user decides if they are acceptable)
  • if BIT_SHIFT -> do a 1st order recovery by reversing the shift (user decides if they are acceptable)
  • OTHER including SENSOR_NOT_READY -> keep previous values as there are no new values.

Keeping the previous values would give the same values during burst of failures as seen in #11 although a single good read in the burst would be an update of H&T.

A variant keeps previous values in case of any error. Simple, straightforward and less code.

Questions

  • Must the library "protect" the users from not checking the return value?
  • Should there be a keep last good read flag to suppress the -999 as value? [interesting]

Thoughts

  • CHECKSUM errors are seldom seen.
  • Reversing BIT_SHIFT errors is not proven, however seems to give acceptable (correct) values. [investigate]
    Reversing BIT_SHIFT errors will give more updates of H&T that are valid [assumption, to investigate] so it would could be a sort of (best effort ) damage control in the burst of failures seen in burst of failures in #11. Note that ~16% of errors in a burst is BIT_SHIFT so it could reduce the interval between failed readings quite a bit.
  • The error value -999 can be replaced by another value that would disrupt graphs less, e.g. -100 would be out of specification and therefor still noticed by the user. The value could also be +125 as that might be even less disruptive. [investigate]

Still problems with measuring negative values (AM2301)

Hello

I am using several senses (dht22, am2301) to manage domotics at home and my outside sense blocked at 0°C when outside temperature was going down during the night.

Actually I tried another set of senses to verify the causes in my fridge and it appears that the two last versions of the library doesn't function quite well with (at least) my am2301 senses

I tried to measure temperatures in the fridge with different descending versions of the library.

When I re-installed the 0.4.3 version it brings correct values.

In facts the 0.4.5 version blocks at 0°C for negative values.
The 0.4.4 version gives me -3267 +/- values when negative.

My two tested boards are arduino nano and uno (both chinese lowcost) and they both give same results.

Perhaps it is linked to your last modifications like in the last issue (#52 ) ...?
Thanks for your work anyway and good luck

Support for DS18B20

Not sure if it makes sense as it is not from the DHT family, but support for DS18B20 would be great so that we can use just one library. Just a thought.

Shows wrong type

I have a DHT11 (the blue sensor), but it shows type "22" in the dhtnew_test sketch.
Temp and Humid readings are OK, though. Is this a known problem?

Humidity values higher than 100%

Hello,

I have recently changed to DHTnew after this thread, and I noticed that completely at random, I get these very high values of humidity. Of course I could just ignore them if higher than 100, but I was wondering what the cause might be.

My setup are two ESP-01s one with DHT22, the other with a DHT11, both send values to an MQTT broker, which are captured by telegraf and stored in an InfluxDB instance.

Humidity values higher than 100%

time temperature humidity location sensor
---- ----------- -------- -------- ------
2021-04-11T23:56:08.272696401Z 8.3 3317.3 Living Room DHT22
2021-04-12T03:37:10.063376651Z 8.4 3316.6 Living Room DHT22
2021-04-12T04:57:10.712664669Z 8.4 3316.5 Living Room DHT22
2021-04-12T07:48:12.095298698Z 8.6 3316 Living Room DHT22
2021-04-12T08:25:42.399491599Z 8.7 3315.7 Living Room DHT22
2021-04-12T09:14:42.796313132Z 8.8 3315.2 Living Room DHT22
2021-04-12T10:23:13.385068097Z 8.9 3315 Living Room DHT22
2021-04-12T11:03:43.682027118Z 9.1 3314.3 Living Room DHT22
2021-04-12T14:58:15.595547784Z 9.2 3317.8 Living Room DHT22
2021-04-12T15:53:46.033386665Z 9.1 3318.4 Living Room DHT22
2021-04-12T15:59:16.076817334Z 9.1 3318.4 Living Room DHT22
2021-04-13T13:36:56.626400588Z 9.3 3317.2 Living Room DHT22
2021-04-13T15:49:57.682886104Z 9.5 3317.1 Living Room DHT22

The graph of the last 48 hours looks like this:
image

Living Room is the DHT22 and Kitchen is DHT11. They are at the same location, side-by-side, despite the names

Any thoughts on why this happens?

Thanks!

DTH11 gets too short start impulse

I just tried this library with a DHT11. Did not work. A test with an oscilloscope showed a LOW pulse of just 3.3ms, while the DHT11 needs 18ms.

The problem seems to be calling delayMicroseconds() with a value larger than 16383: https://www.arduino.cc/reference/en/language/functions/time/delaymicroseconds/

A very simple fix is (line 329 in dhtnew.cpp):

delayMicroseconds(_wakeupDelay * 1100UL);
->
delayMicroseconds(_wakeupDelay * 550UL);
delayMicroseconds(_wakeupDelay * 550UL);

Strange readings

I am using
esp32 ttgo sim 800l (https://rb.gy/ogywnq)
Dfrobot dht22 (https://www.dfrobot.com/product-1102.html)

my code

DHTNEW DHT(18);
DHT.setWaitForReading(true);

float DHTtempBuffer[7];
float DHThumidityBuffer[7];
int DHTReadings = 7;             // number of DHT readings before choosing a median

void getDHT(){
  for (int i = 0 ; i < DHTReadings; i++) {
    DHT.read();                                     // Gets a reading from the DHT sensor
    DHThumidityBuffer[i] = DHT.getHumidity();
    DHTtempBuffer[i] = DHT.getTemperature();
  }
  sortData(DHThumidityBuffer, DHTReadings);                     //sorts array low to high
  DHThumidity = DHThumidityBuffer[(DHTReadings - 1) / 2];       //gets median of the array
  sortData(DHTtempBuffer, DHTReadings);                         //sorts array low to high
  DHTtemperature = DHTtempBuffer[(DHTReadings - 1) / 2];        //gets median of the array
}

So my problem is that even tho I use a filtering algorithm to get rid of highs and lows by taking 7 readings then choosing a median I will occasionally get some massive dips in temperature (and spikes in humidity as a result). my temperature in my room stays about 24°C and the dips are -12 and 12 °C so half the temp and half * -1. I have no clue why it is doing this... It runs every ~2 mins and when the bad readings start it does it consistently for a few runs before correcting itself.

18

Nothing moves nothing is touched nothing changes... It just goes wack... Could it be a library error? I don't see how it could be but you're a smart man @RobTillaart so you may see something I'm missing. I have also thought of the potential that its a dud sensor. I hope not bc i ordered 20 more before testing the one I'm using. I had the thought that maybe adding more reading (like 15 instead of 7) so there is more to data to filter but it looks like all the readings it's taking in those fault zones are bad...

Would appreciate any suggestion - Regards Hale

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.