{"id":13894203,"url":"https://github.com/RobTillaart/DHTNew","last_synced_at":"2025-07-17T09:31:05.528Z","repository":{"id":41546607,"uuid":"254325052","full_name":"RobTillaart/DHTNew","owner":"RobTillaart","description":"Arduino library for DHT11 and DHT22 with automatic sensor recognition","archived":false,"fork":false,"pushed_at":"2025-01-21T18:32:35.000Z","size":197,"stargazers_count":102,"open_issues_count":0,"forks_count":16,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-05-25T18:06:30.801Z","etag":null,"topics":["arduino","humidity","temperature"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RobTillaart.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"RobTillaart","custom":"https://www.paypal.me/robtillaart"}},"created_at":"2020-04-09T09:16:49.000Z","updated_at":"2025-05-06T03:59:10.000Z","dependencies_parsed_at":"2024-03-24T15:36:51.572Z","dependency_job_id":"80a61fe9-0ab6-4739-a949-f10abf5e18f1","html_url":"https://github.com/RobTillaart/DHTNew","commit_stats":null,"previous_names":[],"tags_count":36,"template":false,"template_full_name":null,"purl":"pkg:github/RobTillaart/DHTNew","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobTillaart%2FDHTNew","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobTillaart%2FDHTNew/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobTillaart%2FDHTNew/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobTillaart%2FDHTNew/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RobTillaart","download_url":"https://codeload.github.com/RobTillaart/DHTNew/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobTillaart%2FDHTNew/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265589080,"owners_count":23793464,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arduino","humidity","temperature"],"created_at":"2024-08-06T18:01:26.397Z","updated_at":"2025-07-17T09:31:05.521Z","avatar_url":"https://github.com/RobTillaart.png","language":"C++","funding_links":["https://github.com/sponsors/RobTillaart","https://www.paypal.me/robtillaart"],"categories":["C++"],"sub_categories":[],"readme":"\n[![Arduino CI](https://github.com/RobTillaart/DHTNew/workflows/Arduino%20CI/badge.svg)](https://github.com/marketplace/actions/arduino_ci)\n[![Arduino-lint](https://github.com/RobTillaart/DHTNew/actions/workflows/arduino-lint.yml/badge.svg)](https://github.com/RobTillaart/DHTNew/actions/workflows/arduino-lint.yml)\n[![JSON check](https://github.com/RobTillaart/DHTNew/actions/workflows/jsoncheck.yml/badge.svg)](https://github.com/RobTillaart/DHTNew/actions/workflows/jsoncheck.yml)\n[![GitHub issues](https://img.shields.io/github/issues/RobTillaart/DHTNew.svg)](https://github.com/RobTillaart/DHTNew/issues)\n\n[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/RobTillaart/DHTNew/blob/master/LICENSE)\n[![GitHub release](https://img.shields.io/github/release/RobTillaart/DHTNew.svg?maxAge=3600)](https://github.com/RobTillaart/DHTNew/releases)\n[![PlatformIO Registry](https://badges.registry.platformio.org/packages/robtillaart/library/DHTNew.svg)](https://registry.platformio.org/libraries/robtillaart/DHTNew)\n\n\n# DHTNew\n\nArduino library for DHT11 and DHT22 (and compatible) with automatic sensor type recognition.\n\n\n## Description\n\nDHTNEW is stable for both ARM and AVR. It is based upon the well tested DHTlib code.\nThis is the main development library of all my DHT libraries.\n\nSupports DHT11, DHT22, DHT33, DHT44, AM2301, AM2302, AM2303 as these all have the same protocol.\nNote there are differences e.g. DHT11 has no negative temperature, no decimals, and a longer wakeup time.\n\nThe DHTNew library returns Temperature in degrees Celsius and Humidity in 0.0 - 100.0 %RH.\nFor converting temperature to Fahrenheit or Kelvin, see https://github.com/RobTillaart/Temperature.\n\nFor diagnosis if a DHT sensor gives strange readings one can use **dhtnew_pulse_diag_ext.ino**\nto compare timing with the datasheet.\n\n\n### Sonoff Si7021\n\nSince 0.4.14 there is **experimental** support for the Sonoff Si7021. \nNo hardware yet to test this myself, but it is confirmed to work.\nSee https://github.com/RobTillaart/DHTNew/issues/79.\nSeems the Sonoff Si7021 sensor is very sensitive in the wakeup timing.\nThis behaviour needs to be investigated in the future. \n\nTo use the library one should call **setType(70)**.\n\nFeedback (both positive and negative) about the Sonoff Si7021 sensors is welcome.\n\n\n### AM2320, AM2321 and AM2322\n\nSince 0.4.18 there is **experimental** support for the AM2320, AM2321 and AM2322.\nNot tested myself, but AM2320 is confirmed to work, see https://github.com/RobTillaart/AM232X/issues/26\nAs the AM2321 and AM2322 are quite identical according to the datasheet, those are expected to work too.\n\nTo use the library one should call **setType(22)** as the protocol is identical to the DHT22.\nIf there are differences in operation type (23) will be elaborated.\nThe type 23 is now mapped upon type 22.\n\nFeedback (both positive and negative) about the AM232X sensors is welcome.\n\n**Note: check the datasheet how to connect!**\n\n\n### KY-015 (dht11)\n\nSince 0.5.1 there is support for the KY-015. Although it is a DHT11, the KY-015 behaves slightly \ndifferent (faster wakeup) and was recognized as a DHT22 resulting in faulty conversions.\nThe library sensor recognition code has been adapted so it should be recognized now.\nIn the case the recognition fails, one can use **setType(11)** to force the type.\n\nThe KY-015 is confirmed to work, see https://github.com/RobTillaart/DHTNew/issues/102\n\nFeedback about the KY-015 sensors is welcome.\n\n**Note: check the datasheet how to connect!**\n\n\n### 0.5.0 Negative temperature\n\nApparently there are DHT22's which use another representation for negative temperatures.\nSince 0.5.0 the library automatically detects which representation is used by the sensor\nand chooses the correct algorithm to decode the negative temperature.\n\nSee issue #100 (solution) and #57 and #52 before.  \nSee also https://arduino.stackexchange.com/questions/86448/dht22-sensor-reading-code-interprets-negative-values-weirdly\n\n\n### Related\n\n- https://github.com/RobTillaart/DHTNew DHT11/22 etc\n- https://github.com/RobTillaart/DHTStable DHT11/22 etc\n- https://github.com/RobTillaart/DHT_Simulator\n- https://github.com/RobTillaart/DS18B20_INT OneWire temperature sensor\n- https://github.com/RobTillaart/DS18B20_RT OneWire temperature sensor\n- https://github.com/RobTillaart/SHT31 Sensirion humidity / temperature sensor\n- https://github.com/RobTillaart/SHT85 Sensirion humidity / temperature sensor\n- https://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many.html (interesting)\n- https://github.com/RobTillaart/Temperature (conversions, dewPoint, heat index etc.)\n\n\n## DHT PIN layout from left to right\n\n|  Front  |      |  Description    |\n|:--------|:----:|:----------------|\n|  pin 1  |      |  VCC            |\n|  pin 2  |      |  DATA           |\n|  pin 3  |      |  Not Connected  |\n|  pin 4  |      |  GND            |\n\n**Note: check the datasheet of the sensor how to connect!** as some have only 3 pins.\n\n\n## Specification DHT22\n\nAs most used model, for other sensors I refer to datasheet.\n\n|  Model                      |  DHT22                   |  Notes  |\n|:----------------------------|:-------------------------|:--------|\n|  Power supply               |  3.3 - 6.0 V DC          |\n|  Output signal              |  digital signal via single-bus  |\n|  Sensing element            |  polymer capacitor       |\n|  Operating range            |  humidity 0.0-100.0% RH  |  temperature -40° - 80° Celsius\n|  Accuracy humidity          |  ±2% RH(Max ±5% RH)      |  temperature \u003c ±0.5° Celsius\n|  Resolution or sensitivity  |  humidity 0.1% RH        |  temperature 0.1° Celsius\n|  Repeatability humidity     |  ±1.0% RH                |  temperature ±0.2° Celsius\n|  Humidity hysteresis        |  ±0.3% RH                |\n|  Long-term Stability        |  ±0.5% RH/year           |\n|  Sensing period             |  average: 2 s            |\n|  Interchangeability         |  fully interchangeable   |\n|  Dimensions                 |  small 14 x 18 x 5.5 mm  |  big 22 x 28 x 5 mm  |\n\n\n## Interface\n\n```cpp\n#include \"dhtnew.h\"\n```\n\n### Constructor\n\n- **DHTNEW(uint8_t pin)** defines the dataPin of the sensor.\n- **void reset()** might help to reset a sensor behaving badly. \nIt resets the library internal settings to default, \nhowever it does not reset the sensor in a hardware way. \n- **uint8_t getType()**  0 = unknown, 11 or 22. \nIn case of 0, **getType()** will try to determine type.\nSince 0.4.14 type 70 is added for **experimental** Sonoff Si7021 support.\n- **void setType(uint8_t type = 0)** allows to force the type of the sensor. \n\n|  Type   |  Sensors                  |  Notes  |\n|:-------:|:-------------------------:|:--------|\n|   0     |  not defined              |\n|   11    |  DHT11 DHT12, KY015       |  KY015 needs setType(11)\n|   22    |  DHT22, DHT33, DHT44 a.o  |  most others\n|   23    |  DHT23                    |  mapped to 22 for now\n|   70    |  Sonoff Si7021            |  experimental\n|  other  |  sets to 0                |  0.4.20\n\n\n### Base interface\n\n- **int read()** reads a new temperature (Celsius) and humidity (%RH) from the sensor.\n- **uint32_t lastRead()** returns milliseconds since last **read()**\n- **float getHumidity()** returns last read humidity = 0.0 - 100.0 %RH.\nIn case of an error it returns **DHTLIB_INVALID_VALUE** == -999. \nNote this error value can be suppressed by **setSuppressError(bool)**.\n- **float getTemperature()** returns last read temperature in Celsius.\nRange depends on the sensor.\nIn case of an error it returns **DHTLIB_INVALID_VALUE** == -999. \nNote this error value can be suppressed by **setSuppressError(bool)**.\n\n\n### Offset \n\nAdding offsets works well in normal range however they might introduce \nunder- or overflow at the ends of the sensor range.\n\nHumidity offset is in % RH and is constrained to 0.0 - 100.0 % in the code.\n\nTemperature offset is in degrees Celsius.\nFor temperature a constrain would be type dependant, so it is not done.\nFurthermore by setting the offset to -273.15 one get the **Kelvin** scale.\n\n- **void setHumidityOffset(float offset)** typical \u003c ±5% RH.\n- **void setTemperatureOffset(float offset)** typical \u003c ±2°C.\n- **float getHumidityOffset()** idem.\n- **float getTemperatureOffset()** idem.\n\nThe \"short-named\" offset functions will become obsolete in the future (0.6.0).\n\n- **void setHumOffset(float offset)** typical \u003c ±5% RH.\n- **void setTempOffset(float offset)** typical \u003c ±2°C.\n- **float getHumOffset()** idem.\n- **float getTempOffset()** idem.\n\n\n### Control\n\nFunctions to adjust the communication with the sensor.\n\n- **void setDisableIRQ(bool b )** allows or suppresses interrupts during core \nread function to keep timing as correct as possible. **Note AVR + MKR1010 + Arduino R4**\n- **bool getDisableIRQ()** returns the above setting. Default **true**.\n- **void setWaitForReading(bool b )** flag to enforce a blocking wait. \n- **bool getWaitForReading()** returns the above setting.\n- **void setReadDelay(uint16_t rd = 0)** To tune the time it waits before actual read. \nThis reduces the blocking time. \nDefault depends on type. 1000 ms (dht11) or 2000 ms (dht22). \nset readDelay to 0 will reset to datasheet values AFTER a call to **read()**.\n- **uint16_t getReadDelay()** returns the above setting.\n- **void powerDown()** pulls dataPin down to reduce power consumption\n- **void powerUp()** restarts the sensor, note one must wait up to two seconds.\n- **void setSuppressError(bool b)** suppress error values of -999 =\u003e \nYou need to check the return value of read() instead.  \nThis is used to keep spikes out of your plotter / graphs / logs. \n- **bool getSuppressError()**  returns the above setting.\n\n\n## Operation\n\nSee examples\n\n\n### TIME_OUT\n\nIf consistent TIMOUT_C or TIMEOUT_D occur during reading a sensor, \none could try if allowing interrupts solves the issue **DHT.setDisableIRQ(false)**.\n\nThis solved this problem at least on\n- AVR boards   - is build into the constructor\n- MKR1010 Wifi - see https://github.com/RobTillaart/DHTNew/issues/67\n                 (added as comment in the examples)\n- Arduino R4   - see https://github.com/arduino/uno-r4-library-compatibility/issues/38\n\n\nIn version 0.4.10 the TIMEOUT_C is extended from 70-90 us to even suppress the TIMEOUT_C\neven more. See discussion and tests in https://github.com/RobTillaart/DHTNew/issues/67.\n\n\n### Serial\n\nThe MKR1010Wifi board need to wait for Serial at startup if you want to monitor it \nfrom the IDE. Adding the line ```while(!Serial):``` fixes this. (added to the examples).\n\nThere might be more boards that need this line to work properly.\n\n\n### DHT22 and ESP8266\n\n- The DHT22 sensor has some problems in combination with specific pins of the ESP8266. See more details\n  - https://github.com/RobTillaart/DHTNew/issues/31  (message Jan 3, 2021)\n  - https://github.com/arendst/Tasmota/issues/3522\n\n\n### Voltage AM2301 and ESP8266\n\nIn a test an AM2301 had problems giving no humidity (99.9% overflow) when the\nDHTStable library was used with an ESP8266. (Reported by mail, no GH issue).\nAs this DHTStable library is strongly related to the DHTNew it is mentioned here too.\n\nAfter days of testing and thinking and more testing the cause was found. \nThe AM2301 was powered by a 5V3 power supply which was apparently too high while having the\ndata handshakes at 3V3. \nWhen the VCC voltage was lowered to 5V1 it appeared to work as it should. \n(Kudos to Viktor for finding the cause)\n\n\n## History \n\nDHTNEW has some new features compared to the DHTlib code.\n\n1. The constructor has a pin number, so the one sensor - one object paradigm is chosen.\n   So you can now make a DHTNEW object bathroom(4), kitchen(3), etc.\n2. The **read()** function now reads both DHT11 and DHT22 sensors and selects the right \n   math per sensor based upon the bit patterns. \n3. An **offset** can be set for both temperature and humidity to have a first-order linear\n   calibration in the class itself. Of course, this introduces a possible risk of\n   under- or overflow.\n   For a more elaborated or non-linear offset, I refer to my multimap class.\n4. **lastRead()** keeps track of the last time the sensor is read. If this is not too long ago \n   one can decide not to read the sensors but use the current values for temperature and humidity.\n   This saves up to 20+ milliseconds for a DHT11 or 5+ milliseconds for a DHT22. Note that these sensors \n   should have 1-2 seconds between reads according to specification. \n   In the future, this functionality could be inside the library by setting a time threshold\n   (e.g. 1 second by default) to give more stable results.\n5. Added **interrupt enable/disable flag** to prevent interrupts disturb timing of DHT protocol.\n   Be aware that this may affect other parts of your application.\n6. (0.1.7) added an automatic check of lastRead in the read call. If request a read to fast it will just return OK.\n7. (0.1.7) added **waitForReading flag** (kudos to Mr-HaleYa) to let the sensor explicitly \n   wait until a new value can be read.\n8. (0.2.0) Temperature and humidity are private now, use **getTemperature()** and **getHumidity()**\n9. (0.2.1) Adjusted the bit timing threshold to work around issue #11 \n10. (0.2.2) added **ERROR_SENSOR_NOT_READY** and differentiated timeout errors.\n11. (0.3.0)\nremoved interrupt flag, now the library always disables interrupts during \nthe clocking of the bits.\nAdded getReadDelay \u0026 setReadDelay to tune reading interval. Check the example code.\nAdjusted the timing in the wake-up part of the protocol. \nAdded more comments to describe the protocol.\n12. (0.3.1)\nadded **powerDown()** and **powerUp()** for low power applications. Note that after **powerUp()**\nthe user must wait for two seconds before doing a read(). Just like after a (re)boot.  \nNote: The lib does not (yet) control the power pin of the sensor. \nDiscussion see https://github.com/RobTillaart/DHTNew/issues/13\n13. (0.3.2)\nAdded **setSuppressError()** and **getSuppressError()** so the library will not output -999 \nbut the last known valid value for temperature and humidity. \nThis flag is useful to suppress 'negative spikes' in graphs or logs. \nDefault the error values are not suppressed to be backwards compatible.  \nAdded **#ifndef** around **DHTLIB_INVALID_VALUE** so the default -999 can be overruled\ncompile time to set another error value e.g. -127 or -1 whatever suits the project.\n14. (0.3.3)\nRefactored the low level **readSensor()** as the **BIT SHIFT ERROR** issue #29 and issue #11 popped up again.\nIt was reproduced \"efficiently\" with an ESP32 and by using long wires.\nFixed with an explicit digitalWrite(dataPin, HIGH) + delayMicroseconds() to have enough time between\npulling the line HIGH and polling for the line LOW.\n15. (0.3.4)\nAdded **waitFor(state, timeout)** to more precisely follow the datasheet in terms of timing.\nReintroduced the **interrupt enable/disable flag** as forced noInterrupts()\ncould break the timing of the DHT protocol / micros() - seen on AVR.\n16. (0.4.0)\nAdded **DHTLIB_WAITING_FOR_READ** as return value of read =\u003e minor break of interface\n17. (0.4.1)\nAdded Arduino-CI support + **gettype()** now tries to determine type if not known.\n18. (0.4.2)\nFix negative temperatures. Tested with DHTNew_debug.ino and hex dump in .cpp and a freezer.  \nNote: testing in a freezer is not so good for humidity readings.\n19. (0.4.3)\nAdded **reset()** to reset internal variables when a sensor blocks this might help.\nAdded **lastRead()** to return time the sensor is last read. (in milliseconds).\n20. (0.4.4)\nDO NOT USE incorrect negative temp.\n21. (0.4.5)\nPrevent -0.0 when negative temp is 0;\nDO NOT USE as it maps every negative temp to zero.\n22. (0.4.6) \nFixed negative temperature (again).\n23. (0.4.7)\nfix #60 negative temperatures below -25.5°C + readme.md.\n24. (0.4.8)\nfixes to improve Arduino-lint.\n25. (0.4.9)\nadd optional flag DHTLIB_VALUE_OUT_OF_RANGE.\n26. (0.4.10)\nupdated build-CI to do compile test - UNO, due, zero, Leonardo, m4, esp32, esp8266, mega2560.\nupdated readme.md - added badges and remarks after testing with MKR1010 Wifi.\nupdated TIMEOUT_C from 70 -\u003e 90 us to minimize its occurrence - See https://github.com/RobTillaart/DHTNew/issues/67.\nadded ```while(!Serial);``` in examples to they work for MKR1010 Wifi.\n27. (0.4.11)\nupdate library.json, license, minor edits (clean up), unit tests\n28. (0.4.12)\nFix #72, delayMicroseconds() for wakeUp\n29. (0.4.13)\nFix #76, disable interrupts for ESP32.\n30. (0.4.14)\nadded experimental support for Si7021.\n31. (0.4.15)\nFix #81, recognize DHT22 as type 70. Add minimal wakeup delay.\n32. (0.4.16)\nFix #84 correct the reading of type 70 for Sonoff Si7021.\n33. (0.4.17)\nfix #86, define constants explicit as float.\n34. (0.4.18)\nUpdate readme.md and library.\\* about support for AM2320/21/22.\n35. (0.4.19)\nUpdate readme.md\n36. (0.4.20)\nUpdate GitHub actions and readme.md\n36. (0.4.21)\nAdd dhtnew_pulse_diag_ext.ino\n37. (0.5.0)\nFix negative values\n38. (0.5.1)\nSupport KY015 and more\n38. (0.5.2)\nSupport KY015 (again)\nAdd **DHT_endless_debug.ino** develop example\n38. (0.5.3)\nUpdate readme.md for Arduino R4\n\n\n## Future\n\n#### Must\n\n- update documentation\n\n#### Should\n\n- test on more boards\n- #if defined(MKR1010)  // TODO find out real define  https://github.com/RobTillaart/DHTNew/issues/67\n  ```cpp\n  #ifdef ARDUINO_SAMD_MKRWIFI1010\n  #error found\n  #endif\n  ```\n\n#### Could\n\n- test compatibility =\u003e table.\n- investigate temperature constraining (type dependant)\n\n```cpp\nif (type == 11) temp = constrain(temp,   0, 100);\nif (type == 22) temp = constrain(temp, -40,  80);\netc.\n```\n- type parameter in constructor, default 0\n- reimplement the recognition algorithm (separate class?)\n  - read as 22 =\u003e check the hum / temp data range to determine type\n  - read as 11 =\u003e check idem\n  - read as 70 =\u003e check idem\n  - split wakeup time from bit interpretation used.\n\n#### Wont\n\n- move all code from .h to .cpp\n- derived classes for fixed type?\n\n\n## Support\n\nIf you appreciate my libraries, you can support the development and maintenance.\nImprove the quality of the libraries by providing issues and Pull Requests, or\ndonate through PayPal or GitHub sponsors.\n\nThank you,\n\n ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRobTillaart%2FDHTNew","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRobTillaart%2FDHTNew","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRobTillaart%2FDHTNew/lists"}