├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── githubci.yml ├── .gitignore ├── CONTRIBUTING.md ├── DHT.cpp ├── DHT.h ├── DHT_U.cpp ├── DHT_U.h ├── README.md ├── code-of-conduct.md ├── examples ├── DHT_Unified_Sensor │ └── DHT_Unified_Sensor.ino └── DHTtester │ └── DHTtester.ino ├── keywords.txt ├── library.properties └── license.txt /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for opening an issue on an Adafruit Arduino library repository. To 2 | improve the speed of resolution please review the following guidelines and 3 | common troubleshooting steps below before creating the issue: 4 | 5 | - **Do not use GitHub issues for troubleshooting projects and issues.** Instead use 6 | the forums at http://forums.adafruit.com to ask questions and troubleshoot why 7 | something isn't working as expected. In many cases the problem is a common issue 8 | that you will more quickly receive help from the forum community. GitHub issues 9 | are meant for known defects in the code. If you don't know if there is a defect 10 | in the code then start with troubleshooting on the forum first. 11 | 12 | - **If following a tutorial or guide be sure you didn't miss a step.** Carefully 13 | check all of the steps and commands to run have been followed. Consult the 14 | forum if you're unsure or have questions about steps in a guide/tutorial. 15 | 16 | - **For Arduino projects check these very common issues to ensure they don't apply**: 17 | 18 | - For uploading sketches or communicating with the board make sure you're using 19 | a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes 20 | very hard to tell the difference between a data and charge cable! Try using the 21 | cable with other devices or swapping to another cable to confirm it is not 22 | the problem. 23 | 24 | - **Be sure you are supplying adequate power to the board.** Check the specs of 25 | your board and plug in an external power supply. In many cases just 26 | plugging a board into your computer is not enough to power it and other 27 | peripherals. 28 | 29 | - **Double check all soldering joints and connections.** Flakey connections 30 | cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. 31 | 32 | - **Ensure you are using an official Arduino or Adafruit board.** We can't 33 | guarantee a clone board will have the same functionality and work as expected 34 | with this code and don't support them. 35 | 36 | If you're sure this issue is a defect in the code and checked the steps above 37 | please fill in the following fields to provide enough troubleshooting information. 38 | You may delete the guideline and text above to just leave the following details: 39 | 40 | - Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE** 41 | 42 | - Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO 43 | VERSION HERE** 44 | 45 | - List the steps to reproduce the problem below (if possible attach a sketch or 46 | copy the sketch code in too): **LIST REPRO STEPS BELOW** 47 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for creating a pull request to contribute to Adafruit's GitHub code! 2 | Before you open the request please review the following guidelines and tips to 3 | help it be more easily integrated: 4 | 5 | - **Describe the scope of your change--i.e. what the change does and what parts 6 | of the code were modified.** This will help us understand any risks of integrating 7 | the code. 8 | 9 | - **Describe any known limitations with your change.** For example if the change 10 | doesn't apply to a supported platform of the library please mention it. 11 | 12 | - **Please run any tests or examples that can exercise your modified code.** We 13 | strive to not break users of the code and running tests/examples helps with this 14 | process. 15 | 16 | Thank you again for contributing! We will try to test and integrate the change 17 | as soon as we can, but be aware we have many GitHub repositories to manage and 18 | can't immediately respond to every request. There is no need to bump or check in 19 | on a pull request (it will clutter the discussion of the request). 20 | 21 | Also don't be worried if the request is closed or not integrated--sometimes the 22 | priorities of Adafruit's GitHub code (education, ease of use) might not match the 23 | priorities of the pull request. Don't fret, the open source community thrives on 24 | forks and GitHub makes it easy to keep your changes in a forked repo. 25 | 26 | After reviewing the guidelines above you can delete this text from the pull request. 27 | -------------------------------------------------------------------------------- /.github/workflows/githubci.yml: -------------------------------------------------------------------------------- 1 | name: Arduino Library CI 2 | 3 | on: [pull_request, push, repository_dispatch] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/setup-python@v4 11 | with: 12 | python-version: '3.x' 13 | - uses: actions/checkout@v3 14 | - uses: actions/checkout@v3 15 | with: 16 | repository: adafruit/ci-arduino 17 | path: ci 18 | 19 | - name: pre-install 20 | run: bash ci/actions_install.sh 21 | 22 | - name: test platforms 23 | run: python3 ci/build_platform.py main_platforms 24 | 25 | - name: clang 26 | run: python3 ci/run-clang-format.py -e "ci/*" -e "bin/*" -r . 27 | 28 | - name: doxygen 29 | env: 30 | GH_REPO_TOKEN: ${{ secrets.GH_REPO_TOKEN }} 31 | PRETTYNAME : "DHT sensor library" 32 | run: bash ci/doxy_gen_and_deploy.sh 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # osx 2 | .DS_Store 3 | 4 | # doxygen 5 | Doxyfile* 6 | doxygen_sqlite3.db 7 | html 8 | *.tmp 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidlines 2 | 3 | This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/adafruit/DHT-sensor-library/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community. 4 | 5 | The following are some guidelines to observe when creating issues or PRs: 6 | 7 | - Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas 8 | 9 | - [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets 10 | 11 | - Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile: 12 | 13 | - Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library 14 | -------------------------------------------------------------------------------- /DHT.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DHT.cpp 3 | * 4 | * @mainpage DHT series of low cost temperature/humidity sensors. 5 | * 6 | * @section intro_sec Introduction 7 | * 8 | * This is a library for DHT series of low cost temperature/humidity sensors. 9 | * 10 | * You must have Adafruit Unified Sensor Library library installed to use this 11 | * class. 12 | * 13 | * Adafruit invests time and resources providing this open source code, 14 | * please support Adafruit andopen-source hardware by purchasing products 15 | * from Adafruit! 16 | * 17 | * @section author Author 18 | * 19 | * Written by Adafruit Industries. 20 | * 21 | * @section license License 22 | * 23 | * MIT license, all text above must be included in any redistribution 24 | */ 25 | 26 | #include "DHT.h" 27 | 28 | #define MIN_INTERVAL 2000 /**< min interval value */ 29 | #define TIMEOUT \ 30 | UINT32_MAX /**< Used programmatically for timeout. \ 31 | Not a timeout duration. Type: uint32_t. */ 32 | 33 | /*! 34 | * @brief Instantiates a new DHT class 35 | * @param pin 36 | * pin number that sensor is connected 37 | * @param type 38 | * type of sensor 39 | * @param count 40 | * number of sensors 41 | */ 42 | DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { 43 | (void)count; // Workaround to avoid compiler warning. 44 | _pin = pin; 45 | _type = type; 46 | #ifdef __AVR 47 | _bit = digitalPinToBitMask(pin); 48 | _port = digitalPinToPort(pin); 49 | #endif 50 | _maxcycles = 51 | microsecondsToClockCycles(1000); // 1 millisecond timeout for 52 | // reading pulses from DHT sensor. 53 | // Note that count is now ignored as the DHT reading algorithm adjusts itself 54 | // based on the speed of the processor. 55 | } 56 | 57 | /*! 58 | * @brief Setup sensor pins and set pull timings 59 | * @param usec 60 | * Optionally pass pull-up time (in microseconds) before DHT reading 61 | *starts. Default is 55 (see function declaration in DHT.h). 62 | */ 63 | void DHT::begin(uint8_t usec) { 64 | // set up the pins! 65 | pinMode(_pin, INPUT_PULLUP); 66 | // Using this value makes sure that millis() - lastreadtime will be 67 | // >= MIN_INTERVAL right away. Note that this assignment wraps around, 68 | // but so will the subtraction. 69 | _lastreadtime = millis() - MIN_INTERVAL; 70 | DEBUG_PRINT("DHT max clock cycles: "); 71 | DEBUG_PRINTLN(_maxcycles, DEC); 72 | pullTime = usec; 73 | } 74 | 75 | /*! 76 | * @brief Read temperature 77 | * @param S 78 | * Scale. Boolean value: 79 | * - true = Fahrenheit 80 | * - false = Celcius 81 | * @param force 82 | * true if in force mode 83 | * @return Temperature value in selected scale 84 | */ 85 | float DHT::readTemperature(bool S, bool force) { 86 | float f = NAN; 87 | 88 | if (read(force)) { 89 | switch (_type) { 90 | case DHT11: 91 | f = data[2]; 92 | if (data[3] & 0x80) { 93 | f = -1 - f; 94 | } 95 | f += (data[3] & 0x0f) * 0.1; 96 | if (S) { 97 | f = convertCtoF(f); 98 | } 99 | break; 100 | case DHT12: 101 | f = data[2]; 102 | f += (data[3] & 0x0f) * 0.1; 103 | if (data[2] & 0x80) { 104 | f *= -1; 105 | } 106 | if (S) { 107 | f = convertCtoF(f); 108 | } 109 | break; 110 | case DHT22: 111 | case DHT21: 112 | f = ((word)(data[2] & 0x7F)) << 8 | data[3]; 113 | f *= 0.1; 114 | if (data[2] & 0x80) { 115 | f *= -1; 116 | } 117 | if (S) { 118 | f = convertCtoF(f); 119 | } 120 | break; 121 | } 122 | } 123 | return f; 124 | } 125 | 126 | /*! 127 | * @brief Converts Celcius to Fahrenheit 128 | * @param c 129 | * value in Celcius 130 | * @return float value in Fahrenheit 131 | */ 132 | float DHT::convertCtoF(float c) { return c * 1.8 + 32; } 133 | 134 | /*! 135 | * @brief Converts Fahrenheit to Celcius 136 | * @param f 137 | * value in Fahrenheit 138 | * @return float value in Celcius 139 | */ 140 | float DHT::convertFtoC(float f) { return (f - 32) * 0.55555; } 141 | 142 | /*! 143 | * @brief Read Humidity 144 | * @param force 145 | * force read mode 146 | * @return float value - humidity in percent 147 | */ 148 | float DHT::readHumidity(bool force) { 149 | float f = NAN; 150 | if (read(force)) { 151 | switch (_type) { 152 | case DHT11: 153 | case DHT12: 154 | f = data[0] + data[1] * 0.1; 155 | break; 156 | case DHT22: 157 | case DHT21: 158 | f = ((word)data[0]) << 8 | data[1]; 159 | f *= 0.1; 160 | break; 161 | } 162 | } 163 | return f; 164 | } 165 | 166 | /*! 167 | * @brief Compute Heat Index 168 | * Simplified version that reads temp and humidity from sensor 169 | * @param isFahrenheit 170 | * true if fahrenheit, false if celcius 171 | *(default true) 172 | * @return float heat index 173 | */ 174 | float DHT::computeHeatIndex(bool isFahrenheit) { 175 | float hi = computeHeatIndex(readTemperature(isFahrenheit), readHumidity(), 176 | isFahrenheit); 177 | return hi; 178 | } 179 | 180 | /*! 181 | * @brief Compute Heat Index 182 | * Using both Rothfusz and Steadman's equations 183 | * (http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml) 184 | * @param temperature 185 | * temperature in selected scale 186 | * @param percentHumidity 187 | * humidity in percent 188 | * @param isFahrenheit 189 | * true if fahrenheit, false if celcius 190 | * @return float heat index 191 | */ 192 | float DHT::computeHeatIndex(float temperature, float percentHumidity, 193 | bool isFahrenheit) { 194 | float hi; 195 | 196 | if (!isFahrenheit) 197 | temperature = convertCtoF(temperature); 198 | 199 | hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + 200 | (percentHumidity * 0.094)); 201 | 202 | if (hi > 79) { 203 | hi = -42.379 + 2.04901523 * temperature + 10.14333127 * percentHumidity + 204 | -0.22475541 * temperature * percentHumidity + 205 | -0.00683783 * pow(temperature, 2) + 206 | -0.05481717 * pow(percentHumidity, 2) + 207 | 0.00122874 * pow(temperature, 2) * percentHumidity + 208 | 0.00085282 * temperature * pow(percentHumidity, 2) + 209 | -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2); 210 | 211 | if ((percentHumidity < 13) && (temperature >= 80.0) && 212 | (temperature <= 112.0)) 213 | hi -= ((13.0 - percentHumidity) * 0.25) * 214 | sqrt((17.0 - abs(temperature - 95.0)) * 0.05882); 215 | 216 | else if ((percentHumidity > 85.0) && (temperature >= 80.0) && 217 | (temperature <= 87.0)) 218 | hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2); 219 | } 220 | 221 | return isFahrenheit ? hi : convertFtoC(hi); 222 | } 223 | 224 | /*! 225 | * @brief Read value from sensor or return last one from less than two 226 | *seconds. 227 | * @param force 228 | * true if using force mode 229 | * @return float value 230 | */ 231 | bool DHT::read(bool force) { 232 | // Check if sensor was read less than two seconds ago and return early 233 | // to use last reading. 234 | uint32_t currenttime = millis(); 235 | if (!force && ((currenttime - _lastreadtime) < MIN_INTERVAL)) { 236 | return _lastresult; // return last correct measurement 237 | } 238 | _lastreadtime = currenttime; 239 | 240 | // Reset 40 bits of received data to zero. 241 | data[0] = data[1] = data[2] = data[3] = data[4] = 0; 242 | 243 | #if defined(ESP8266) 244 | yield(); // Handle WiFi / reset software watchdog 245 | #endif 246 | 247 | // Send start signal. See DHT datasheet for full signal diagram: 248 | // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf 249 | 250 | // Go into high impedence state to let pull-up raise data line level and 251 | // start the reading process. 252 | pinMode(_pin, INPUT_PULLUP); 253 | delay(1); 254 | 255 | // First set data line low for a period according to sensor type 256 | pinMode(_pin, OUTPUT); 257 | digitalWrite(_pin, LOW); 258 | switch (_type) { 259 | case DHT22: 260 | case DHT21: 261 | delayMicroseconds(1100); // data sheet says "at least 1ms" 262 | break; 263 | case DHT11: 264 | default: 265 | delay(20); // data sheet says at least 18ms, 20ms just to be safe 266 | break; 267 | } 268 | 269 | uint32_t cycles[80]; 270 | { 271 | // End the start signal by setting data line high for 40 microseconds. 272 | pinMode(_pin, INPUT_PULLUP); 273 | 274 | // Delay a moment to let sensor pull data line low. 275 | delayMicroseconds(pullTime); 276 | 277 | // Now start reading the data line to get the value from the DHT sensor. 278 | 279 | // Turn off interrupts temporarily because the next sections 280 | // are timing critical and we don't want any interruptions. 281 | InterruptLock lock; 282 | 283 | // First expect a low signal for ~80 microseconds followed by a high signal 284 | // for ~80 microseconds again. 285 | if (expectPulse(LOW) == TIMEOUT) { 286 | DEBUG_PRINTLN(F("DHT timeout waiting for start signal low pulse.")); 287 | _lastresult = false; 288 | return _lastresult; 289 | } 290 | if (expectPulse(HIGH) == TIMEOUT) { 291 | DEBUG_PRINTLN(F("DHT timeout waiting for start signal high pulse.")); 292 | _lastresult = false; 293 | return _lastresult; 294 | } 295 | 296 | // Now read the 40 bits sent by the sensor. Each bit is sent as a 50 297 | // microsecond low pulse followed by a variable length high pulse. If the 298 | // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds 299 | // then it's a 1. We measure the cycle count of the initial 50us low pulse 300 | // and use that to compare to the cycle count of the high pulse to determine 301 | // if the bit is a 0 (high state cycle count < low state cycle count), or a 302 | // 1 (high state cycle count > low state cycle count). Note that for speed 303 | // all the pulses are read into a array and then examined in a later step. 304 | for (int i = 0; i < 80; i += 2) { 305 | cycles[i] = expectPulse(LOW); 306 | cycles[i + 1] = expectPulse(HIGH); 307 | } 308 | } // Timing critical code is now complete. 309 | 310 | // Inspect pulses and determine which ones are 0 (high state cycle count < low 311 | // state cycle count), or 1 (high state cycle count > low state cycle count). 312 | for (int i = 0; i < 40; ++i) { 313 | uint32_t lowCycles = cycles[2 * i]; 314 | uint32_t highCycles = cycles[2 * i + 1]; 315 | if ((lowCycles == TIMEOUT) || (highCycles == TIMEOUT)) { 316 | DEBUG_PRINTLN(F("DHT timeout waiting for pulse.")); 317 | _lastresult = false; 318 | return _lastresult; 319 | } 320 | data[i / 8] <<= 1; 321 | // Now compare the low and high cycle times to see if the bit is a 0 or 1. 322 | if (highCycles > lowCycles) { 323 | // High cycles are greater than 50us low cycle count, must be a 1. 324 | data[i / 8] |= 1; 325 | } 326 | // Else high cycles are less than (or equal to, a weird case) the 50us low 327 | // cycle count so this must be a zero. Nothing needs to be changed in the 328 | // stored data. 329 | } 330 | 331 | DEBUG_PRINTLN(F("Received from DHT:")); 332 | DEBUG_PRINT(data[0], HEX); 333 | DEBUG_PRINT(F(", ")); 334 | DEBUG_PRINT(data[1], HEX); 335 | DEBUG_PRINT(F(", ")); 336 | DEBUG_PRINT(data[2], HEX); 337 | DEBUG_PRINT(F(", ")); 338 | DEBUG_PRINT(data[3], HEX); 339 | DEBUG_PRINT(F(", ")); 340 | DEBUG_PRINT(data[4], HEX); 341 | DEBUG_PRINT(F(" =? ")); 342 | DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX); 343 | 344 | // Check we read 40 bits and that the checksum matches. 345 | if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) { 346 | _lastresult = true; 347 | return _lastresult; 348 | } else { 349 | DEBUG_PRINTLN(F("DHT checksum failure!")); 350 | _lastresult = false; 351 | return _lastresult; 352 | } 353 | } 354 | 355 | // Expect the signal line to be at the specified level for a period of time and 356 | // return a count of loop cycles spent at that level (this cycle count can be 357 | // used to compare the relative time of two pulses). If more than a millisecond 358 | // ellapses without the level changing then the call fails with a 0 response. 359 | // This is adapted from Arduino's pulseInLong function (which is only available 360 | // in the very latest IDE versions): 361 | // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c 362 | uint32_t DHT::expectPulse(bool level) { 363 | // F_CPU is not be known at compile time on platforms such as STM32F103. 364 | // The preprocessor seems to evaluate it to zero in that case. 365 | #if (F_CPU > 16000000L) || (F_CPU == 0L) 366 | uint32_t count = 0; 367 | #else 368 | uint16_t count = 0; // To work fast enough on slower AVR boards 369 | #endif 370 | // On AVR platforms use direct GPIO port access as it's much faster and better 371 | // for catching pulses that are 10's of microseconds in length: 372 | #ifdef __AVR 373 | uint8_t portState = level ? _bit : 0; 374 | while ((*portInputRegister(_port) & _bit) == portState) { 375 | if (count++ >= _maxcycles) { 376 | return TIMEOUT; // Exceeded timeout, fail. 377 | } 378 | } 379 | // Otherwise fall back to using digitalRead (this seems to be necessary on 380 | // ESP8266 right now, perhaps bugs in direct port access functions?). 381 | #else 382 | while (digitalRead(_pin) == level) { 383 | if (count++ >= _maxcycles) { 384 | return TIMEOUT; // Exceeded timeout, fail. 385 | } 386 | } 387 | #endif 388 | 389 | return count; 390 | } 391 | -------------------------------------------------------------------------------- /DHT.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DHT.h 3 | * 4 | * This is a library for DHT series of low cost temperature/humidity sensors. 5 | * 6 | * You must have Adafruit Unified Sensor Library library installed to use this 7 | * class. 8 | * 9 | * Adafruit invests time and resources providing this open source code, 10 | * please support Adafruit andopen-source hardware by purchasing products 11 | * from Adafruit! 12 | * 13 | * Written by Adafruit Industries. 14 | * 15 | * MIT license, all text above must be included in any redistribution 16 | */ 17 | 18 | #ifndef DHT_H 19 | #define DHT_H 20 | 21 | #include "Arduino.h" 22 | 23 | /* Uncomment to enable printing out nice debug messages. */ 24 | //#define DHT_DEBUG 25 | 26 | #define DEBUG_PRINTER \ 27 | Serial /**< Define where debug output will be printed. \ 28 | */ 29 | 30 | /* Setup debug printing macros. */ 31 | #ifdef DHT_DEBUG 32 | #define DEBUG_PRINT(...) \ 33 | { DEBUG_PRINTER.print(__VA_ARGS__); } 34 | #define DEBUG_PRINTLN(...) \ 35 | { DEBUG_PRINTER.println(__VA_ARGS__); } 36 | #else 37 | #define DEBUG_PRINT(...) \ 38 | {} /**< Debug Print Placeholder if Debug is disabled */ 39 | #define DEBUG_PRINTLN(...) \ 40 | {} /**< Debug Print Line Placeholder if Debug is disabled */ 41 | #endif 42 | 43 | /* Define types of sensors. */ 44 | static const uint8_t DHT11{11}; /**< DHT TYPE 11 */ 45 | static const uint8_t DHT12{12}; /**< DHY TYPE 12 */ 46 | static const uint8_t DHT21{21}; /**< DHT TYPE 21 */ 47 | static const uint8_t DHT22{22}; /**< DHT TYPE 22 */ 48 | static const uint8_t AM2301{21}; /**< AM2301 */ 49 | 50 | #if defined(TARGET_NAME) && (TARGET_NAME == ARDUINO_NANO33BLE) 51 | #ifndef microsecondsToClockCycles 52 | /*! 53 | * As of 7 Sep 2020 the Arduino Nano 33 BLE boards do not have 54 | * microsecondsToClockCycles defined. 55 | */ 56 | #define microsecondsToClockCycles(a) ((a) * (SystemCoreClock / 1000000L)) 57 | #endif 58 | #endif 59 | 60 | /*! 61 | * @brief Class that stores state and functions for DHT 62 | */ 63 | class DHT { 64 | public: 65 | DHT(uint8_t pin, uint8_t type, uint8_t count = 6); 66 | void begin(uint8_t usec = 55); 67 | float readTemperature(bool S = false, bool force = false); 68 | float convertCtoF(float); 69 | float convertFtoC(float); 70 | float computeHeatIndex(bool isFahrenheit = true); 71 | float computeHeatIndex(float temperature, float percentHumidity, 72 | bool isFahrenheit = true); 73 | float readHumidity(bool force = false); 74 | bool read(bool force = false); 75 | 76 | private: 77 | uint8_t data[5]; 78 | uint8_t _pin, _type; 79 | #ifdef __AVR 80 | // Use direct GPIO access on an 8-bit AVR so keep track of the port and 81 | // bitmask for the digital pin connected to the DHT. Other platforms will use 82 | // digitalRead. 83 | uint8_t _bit, _port; 84 | #endif 85 | uint32_t _lastreadtime, _maxcycles; 86 | bool _lastresult; 87 | uint8_t pullTime; // Time (in usec) to pull up data line before reading 88 | 89 | uint32_t expectPulse(bool level); 90 | }; 91 | 92 | /*! 93 | * @brief Class that defines Interrupt Lock Avaiability 94 | */ 95 | class InterruptLock { 96 | public: 97 | InterruptLock() { 98 | #if !defined(ARDUINO_ARCH_NRF52) 99 | noInterrupts(); 100 | #endif 101 | } 102 | ~InterruptLock() { 103 | #if !defined(ARDUINO_ARCH_NRF52) 104 | interrupts(); 105 | #endif 106 | } 107 | }; 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /DHT_U.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DHT_U.cpp 3 | * 4 | * Temperature & Humidity Unified Sensor Library 5 | * 6 | * This is a library for DHT series of low cost temperature/humidity sensors. 7 | * 8 | * You must have Adafruit Unified Sensor Library library installed to use this 9 | * class. 10 | * 11 | * Adafruit invests time and resources providing this open source code, 12 | * please support Adafruit andopen-source hardware by purchasing products 13 | * from Adafruit! 14 | */ 15 | #include "DHT_U.h" 16 | 17 | /*! 18 | * @brief Instantiates a new DHT_Unified class 19 | * @param pin 20 | * pin number that sensor is connected 21 | * @param type 22 | * type of sensor 23 | * @param count 24 | * number of sensors 25 | * @param tempSensorId 26 | * temperature sensor id 27 | * @param humiditySensorId 28 | * humidity sensor id 29 | */ 30 | DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, 31 | int32_t tempSensorId, int32_t humiditySensorId) 32 | : _dht(pin, type, count), _type(type), _temp(this, tempSensorId), 33 | _humidity(this, humiditySensorId) {} 34 | 35 | /*! 36 | * @brief Setup sensor (calls begin on It) 37 | */ 38 | void DHT_Unified::begin() { _dht.begin(); } 39 | 40 | /*! 41 | * @brief Sets sensor name 42 | * @param sensor 43 | * Sensor that will be set 44 | */ 45 | void DHT_Unified::setName(sensor_t *sensor) { 46 | switch (_type) { 47 | case DHT11: 48 | strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1); 49 | break; 50 | case DHT12: 51 | strncpy(sensor->name, "DHT12", sizeof(sensor->name) - 1); 52 | break; 53 | case DHT21: 54 | strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1); 55 | break; 56 | case DHT22: 57 | strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1); 58 | break; 59 | default: 60 | // TODO: Perhaps this should be an error? However main DHT library doesn't 61 | // enforce restrictions on the sensor type value. Pick a generic name for 62 | // now. 63 | strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1); 64 | break; 65 | } 66 | sensor->name[sizeof(sensor->name) - 1] = 0; 67 | } 68 | 69 | /*! 70 | * @brief Sets Minimum Delay Value 71 | * @param sensor 72 | * Sensor that will be set 73 | */ 74 | void DHT_Unified::setMinDelay(sensor_t *sensor) { 75 | switch (_type) { 76 | case DHT11: 77 | sensor->min_delay = 1000000L; // 1 second (in microseconds) 78 | break; 79 | case DHT12: 80 | sensor->min_delay = 2000000L; // 2 second (in microseconds) 81 | break; 82 | case DHT21: 83 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 84 | break; 85 | case DHT22: 86 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 87 | break; 88 | default: 89 | // Default to slowest sample rate in case of unknown type. 90 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 91 | break; 92 | } 93 | } 94 | 95 | /*! 96 | * @brief Instantiates a new DHT_Unified Temperature Class 97 | * @param parent 98 | * Parent Sensor 99 | * @param id 100 | * Sensor id 101 | */ 102 | DHT_Unified::Temperature::Temperature(DHT_Unified *parent, int32_t id) 103 | : _parent(parent), _id(id) {} 104 | 105 | /*! 106 | * @brief Reads the sensor and returns the data as a sensors_event_t 107 | * @param event 108 | * @return always returns true 109 | */ 110 | bool DHT_Unified::Temperature::getEvent(sensors_event_t *event) { 111 | // Clear event definition. 112 | memset(event, 0, sizeof(sensors_event_t)); 113 | // Populate sensor reading values. 114 | event->version = sizeof(sensors_event_t); 115 | event->sensor_id = _id; 116 | event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; 117 | event->timestamp = millis(); 118 | event->temperature = _parent->_dht.readTemperature(); 119 | 120 | return true; 121 | } 122 | 123 | /*! 124 | * @brief Provides the sensor_t data for this sensor 125 | * @param sensor 126 | */ 127 | void DHT_Unified::Temperature::getSensor(sensor_t *sensor) { 128 | // Clear sensor definition. 129 | memset(sensor, 0, sizeof(sensor_t)); 130 | // Set sensor name. 131 | _parent->setName(sensor); 132 | // Set version and ID 133 | sensor->version = DHT_SENSOR_VERSION; 134 | sensor->sensor_id = _id; 135 | // Set type and characteristics. 136 | sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; 137 | _parent->setMinDelay(sensor); 138 | switch (_parent->_type) { 139 | case DHT11: 140 | sensor->max_value = 50.0F; 141 | sensor->min_value = 0.0F; 142 | sensor->resolution = 2.0F; 143 | break; 144 | case DHT12: 145 | sensor->max_value = 60.0F; 146 | sensor->min_value = -20.0F; 147 | sensor->resolution = 0.5F; 148 | break; 149 | case DHT21: 150 | sensor->max_value = 80.0F; 151 | sensor->min_value = -40.0F; 152 | sensor->resolution = 0.1F; 153 | break; 154 | case DHT22: 155 | sensor->max_value = 125.0F; 156 | sensor->min_value = -40.0F; 157 | sensor->resolution = 0.1F; 158 | break; 159 | default: 160 | // Unknown type, default to 0. 161 | sensor->max_value = 0.0F; 162 | sensor->min_value = 0.0F; 163 | sensor->resolution = 0.0F; 164 | break; 165 | } 166 | } 167 | 168 | /*! 169 | * @brief Instantiates a new DHT_Unified Humidity Class 170 | * @param parent 171 | * Parent Sensor 172 | * @param id 173 | * Sensor id 174 | */ 175 | DHT_Unified::Humidity::Humidity(DHT_Unified *parent, int32_t id) 176 | : _parent(parent), _id(id) {} 177 | 178 | /*! 179 | * @brief Reads the sensor and returns the data as a sensors_event_t 180 | * @param event 181 | * @return always returns true 182 | */ 183 | bool DHT_Unified::Humidity::getEvent(sensors_event_t *event) { 184 | // Clear event definition. 185 | memset(event, 0, sizeof(sensors_event_t)); 186 | // Populate sensor reading values. 187 | event->version = sizeof(sensors_event_t); 188 | event->sensor_id = _id; 189 | event->type = SENSOR_TYPE_RELATIVE_HUMIDITY; 190 | event->timestamp = millis(); 191 | event->relative_humidity = _parent->_dht.readHumidity(); 192 | 193 | return true; 194 | } 195 | 196 | /*! 197 | * @brief Provides the sensor_t data for this sensor 198 | * @param sensor 199 | */ 200 | void DHT_Unified::Humidity::getSensor(sensor_t *sensor) { 201 | // Clear sensor definition. 202 | memset(sensor, 0, sizeof(sensor_t)); 203 | // Set sensor name. 204 | _parent->setName(sensor); 205 | // Set version and ID 206 | sensor->version = DHT_SENSOR_VERSION; 207 | sensor->sensor_id = _id; 208 | // Set type and characteristics. 209 | sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY; 210 | _parent->setMinDelay(sensor); 211 | switch (_parent->_type) { 212 | case DHT11: 213 | sensor->max_value = 80.0F; 214 | sensor->min_value = 20.0F; 215 | sensor->resolution = 5.0F; 216 | break; 217 | case DHT12: 218 | sensor->max_value = 95.0F; 219 | sensor->min_value = 20.0F; 220 | sensor->resolution = 5.0F; 221 | break; 222 | case DHT21: 223 | sensor->max_value = 100.0F; 224 | sensor->min_value = 0.0F; 225 | sensor->resolution = 0.1F; 226 | break; 227 | case DHT22: 228 | sensor->max_value = 100.0F; 229 | sensor->min_value = 0.0F; 230 | sensor->resolution = 0.1F; 231 | break; 232 | default: 233 | // Unknown type, default to 0. 234 | sensor->max_value = 0.0F; 235 | sensor->min_value = 0.0F; 236 | sensor->resolution = 0.0F; 237 | break; 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /DHT_U.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DHT_U.h 3 | * 4 | * DHT Temperature & Humidity Unified Sensor Library 5 | * 6 | * Adafruit invests time and resources providing this open source code, 7 | * please support Adafruit andopen-source hardware by purchasing products 8 | * from Adafruit! 9 | * 10 | * Written by Tony DiCola (Adafruit Industries) 2014. 11 | * 12 | * MIT license, all text above must be included in any redistribution 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining a copy 15 | * of this software and associated documentation files (the "Software"), to 16 | * deal in the Software without restriction, including without limitation the 17 | * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 18 | * sell copies of the Software, and to permit persons to whom the Software is 19 | * furnished to do so, subject to the following conditions: 20 | * 21 | * The above copyright notice and this permission notice shall be included in 22 | * all copies or substantial portions of the Software. 23 | * 24 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 25 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 26 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 27 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 28 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 29 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 30 | * IN THE SOFTWARE. 31 | */ 32 | 33 | #ifndef DHT_U_H 34 | #define DHT_U_H 35 | 36 | #include 37 | #include 38 | 39 | #define DHT_SENSOR_VERSION 1 /**< Sensor Version */ 40 | 41 | /*! 42 | * @brief Class that stores state and functions for interacting with 43 | * DHT_Unified. 44 | */ 45 | class DHT_Unified { 46 | public: 47 | DHT_Unified(uint8_t pin, uint8_t type, uint8_t count = 6, 48 | int32_t tempSensorId = -1, int32_t humiditySensorId = -1); 49 | void begin(); 50 | 51 | /*! 52 | * @brief Class that stores state and functions about Temperature 53 | */ 54 | class Temperature : public Adafruit_Sensor { 55 | public: 56 | Temperature(DHT_Unified *parent, int32_t id); 57 | bool getEvent(sensors_event_t *event); 58 | void getSensor(sensor_t *sensor); 59 | 60 | private: 61 | DHT_Unified *_parent; 62 | int32_t _id; 63 | }; 64 | 65 | /*! 66 | * @brief Class that stores state and functions about Humidity 67 | */ 68 | class Humidity : public Adafruit_Sensor { 69 | public: 70 | Humidity(DHT_Unified *parent, int32_t id); 71 | bool getEvent(sensors_event_t *event); 72 | void getSensor(sensor_t *sensor); 73 | 74 | private: 75 | DHT_Unified *_parent; 76 | int32_t _id; 77 | }; 78 | 79 | /*! 80 | * @brief Returns temperature stored in _temp 81 | * @return Temperature value 82 | */ 83 | Temperature temperature() { return _temp; } 84 | 85 | /*! 86 | * @brief Returns humidity stored in _humidity 87 | * @return Humidity value 88 | */ 89 | Humidity humidity() { return _humidity; } 90 | 91 | private: 92 | DHT _dht; 93 | uint8_t _type; 94 | Temperature _temp; 95 | Humidity _humidity; 96 | 97 | void setName(sensor_t *sensor); 98 | void setMinDelay(sensor_t *sensor); 99 | }; 100 | 101 | #endif 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DHT sensor library [![Build Status](https://github.com/adafruit/DHT-sensor-library/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/DHT-sensor-library/actions) 2 | 3 | ## Description 4 | 5 | An Arduino library for the DHT series of low-cost temperature/humidity sensors. 6 | 7 | You can find DHT tutorials [here](https://learn.adafruit.com/dht). 8 | 9 | # Dependencies 10 | * [Adafruit Unified Sensor Driver](https://github.com/adafruit/Adafruit_Sensor) 11 | 12 | # Contributing 13 | 14 | Contributions are welcome! Not only you’ll encourage the development of the library, but you’ll also learn how to best use the library and probably some C++ too 15 | 16 | Please read our [Code of Conduct](https://github.com/adafruit/DHT-sensor-library/blob/master/CODE_OF_CONDUCT.md>) 17 | before contributing to help this project stay welcoming. 18 | 19 | ## Documentation and doxygen 20 | Documentation is produced by doxygen. Contributions should include documentation for any new code added. 21 | 22 | Some examples of how to use doxygen can be found in these guide pages: 23 | 24 | https://learn.adafruit.com/the-well-automated-arduino-library/doxygen 25 | 26 | https://learn.adafruit.com/the-well-automated-arduino-library/doxygen-tips 27 | 28 | Written by Adafruit Industries based on work by: 29 | 30 | * T. DiCola 31 | * P. Y. Dragon 32 | * L. Fried 33 | * J. Hoffmann 34 | * M. Kooijman 35 | * J. M. Dana 36 | * S. Conaway 37 | * S. IJskes 38 | * T. Forbes 39 | * B. C 40 | * T. J Myers 41 | * L. Sørup 42 | * per1234 43 | * O. Duffy 44 | * matthiasdanner 45 | * J. Lim 46 | * G. Ambrozio 47 | * chelmi 48 | * adams13x13 49 | * Spacefish 50 | * I. Scheller 51 | * C. Miller 52 | * 7eggert 53 | 54 | 55 | MIT license, check license.txt for more information 56 | All text above must be included in any redistribution 57 | 58 | To install, use the Arduino Library Manager and search for "DHT sensor library" and install the library. 59 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Adafruit Community Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and leaders pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level or type of 9 | experience, education, socio-economic status, nationality, personal appearance, 10 | race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | We are committed to providing a friendly, safe and welcoming environment for 15 | all. 16 | 17 | Examples of behavior that contributes to creating a positive environment 18 | include: 19 | 20 | * Be kind and courteous to others 21 | * Using welcoming and inclusive language 22 | * Being respectful of differing viewpoints and experiences 23 | * Collaborating with other community members 24 | * Gracefully accepting constructive criticism 25 | * Focusing on what is best for the community 26 | * Showing empathy towards other community members 27 | 28 | Examples of unacceptable behavior by participants include: 29 | 30 | * The use of sexualized language or imagery and sexual attention or advances 31 | * The use of inappropriate images, including in a community member's avatar 32 | * The use of inappropriate language, including in a community member's nickname 33 | * Any spamming, flaming, baiting or other attention-stealing behavior 34 | * Excessive or unwelcome helping; answering outside the scope of the question 35 | asked 36 | * Trolling, insulting/derogatory comments, and personal or political attacks 37 | * Public or private harassment 38 | * Publishing others' private information, such as a physical or electronic 39 | address, without explicit permission 40 | * Other conduct which could reasonably be considered inappropriate 41 | 42 | The goal of the standards and moderation guidelines outlined here is to build 43 | and maintain a respectful community. We ask that you don’t just aim to be 44 | "technically unimpeachable", but rather try to be your best self. 45 | 46 | We value many things beyond technical expertise, including collaboration and 47 | supporting others within our community. Providing a positive experience for 48 | other community members can have a much more significant impact than simply 49 | providing the correct answer. 50 | 51 | ## Our Responsibilities 52 | 53 | Project leaders are responsible for clarifying the standards of acceptable 54 | behavior and are expected to take appropriate and fair corrective action in 55 | response to any instances of unacceptable behavior. 56 | 57 | Project leaders have the right and responsibility to remove, edit, or 58 | reject messages, comments, commits, code, issues, and other contributions 59 | that are not aligned to this Code of Conduct, or to ban temporarily or 60 | permanently any community member for other behaviors that they deem 61 | inappropriate, threatening, offensive, or harmful. 62 | 63 | ## Moderation 64 | 65 | Instances of behaviors that violate the Adafruit Community Code of Conduct 66 | may be reported by any member of the community. Community members are 67 | encouraged to report these situations, including situations they witness 68 | involving other community members. 69 | 70 | You may report in the following ways: 71 | 72 | In any situation, you may send an email to . 73 | 74 | On the Adafruit Discord, you may send an open message from any channel 75 | to all Community Helpers by tagging @community helpers. You may also send an 76 | open message from any channel, or a direct message to @kattni#1507, 77 | @tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or 78 | @Andon#8175. 79 | 80 | Email and direct message reports will be kept confidential. 81 | 82 | In situations on Discord where the issue is particularly egregious, possibly 83 | illegal, requires immediate action, or violates the Discord terms of service, 84 | you should also report the message directly to Discord. 85 | 86 | These are the steps for upholding our community’s standards of conduct. 87 | 88 | 1. Any member of the community may report any situation that violates the 89 | Adafruit Community Code of Conduct. All reports will be reviewed and 90 | investigated. 91 | 2. If the behavior is an egregious violation, the community member who 92 | committed the violation may be banned immediately, without warning. 93 | 3. Otherwise, moderators will first respond to such behavior with a warning. 94 | 4. Moderators follow a soft "three strikes" policy - the community member may 95 | be given another chance, if they are receptive to the warning and change their 96 | behavior. 97 | 5. If the community member is unreceptive or unreasonable when warned by a 98 | moderator, or the warning goes unheeded, they may be banned for a first or 99 | second offense. Repeated offenses will result in the community member being 100 | banned. 101 | 102 | ## Scope 103 | 104 | This Code of Conduct and the enforcement policies listed above apply to all 105 | Adafruit Community venues. This includes but is not limited to any community 106 | spaces (both public and private), the entire Adafruit Discord server, and 107 | Adafruit GitHub repositories. Examples of Adafruit Community spaces include 108 | but are not limited to meet-ups, audio chats on the Adafruit Discord, or 109 | interaction at a conference. 110 | 111 | This Code of Conduct applies both within project spaces and in public spaces 112 | when an individual is representing the project or its community. As a community 113 | member, you are representing our community, and are expected to behave 114 | accordingly. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 1.4, available at 120 | , 121 | and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). 122 | 123 | For other projects adopting the Adafruit Community Code of 124 | Conduct, please contact the maintainers of those projects for enforcement. 125 | If you wish to use this code of conduct for your own project, consider 126 | explicitly mentioning your moderation policy or making a copy with your 127 | own moderation policy so as to avoid confusion. 128 | -------------------------------------------------------------------------------- /examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino: -------------------------------------------------------------------------------- 1 | // DHT Temperature & Humidity Sensor 2 | // Unified Sensor Library Example 3 | // Written by Tony DiCola for Adafruit Industries 4 | // Released under an MIT license. 5 | 6 | // REQUIRES the following Arduino libraries: 7 | // - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library 8 | // - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #define DHTPIN 2 // Digital pin connected to the DHT sensor 15 | // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 -- 16 | // Pin 15 can work but DHT must be disconnected during program upload. 17 | 18 | // Uncomment the type of sensor in use: 19 | //#define DHTTYPE DHT11 // DHT 11 20 | #define DHTTYPE DHT22 // DHT 22 (AM2302) 21 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 22 | 23 | // See guide for details on sensor wiring and usage: 24 | // https://learn.adafruit.com/dht/overview 25 | 26 | DHT_Unified dht(DHTPIN, DHTTYPE); 27 | 28 | uint32_t delayMS; 29 | 30 | void setup() { 31 | Serial.begin(9600); 32 | // Initialize device. 33 | dht.begin(); 34 | Serial.println(F("DHTxx Unified Sensor Example")); 35 | // Print temperature sensor details. 36 | sensor_t sensor; 37 | dht.temperature().getSensor(&sensor); 38 | Serial.println(F("------------------------------------")); 39 | Serial.println(F("Temperature Sensor")); 40 | Serial.print (F("Sensor Type: ")); Serial.println(sensor.name); 41 | Serial.print (F("Driver Ver: ")); Serial.println(sensor.version); 42 | Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id); 43 | Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("°C")); 44 | Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("°C")); 45 | Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("°C")); 46 | Serial.println(F("------------------------------------")); 47 | // Print humidity sensor details. 48 | dht.humidity().getSensor(&sensor); 49 | Serial.println(F("Humidity Sensor")); 50 | Serial.print (F("Sensor Type: ")); Serial.println(sensor.name); 51 | Serial.print (F("Driver Ver: ")); Serial.println(sensor.version); 52 | Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id); 53 | Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("%")); 54 | Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("%")); 55 | Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("%")); 56 | Serial.println(F("------------------------------------")); 57 | // Set delay between sensor readings based on sensor details. 58 | delayMS = sensor.min_delay / 1000; 59 | } 60 | 61 | void loop() { 62 | // Delay between measurements. 63 | delay(delayMS); 64 | // Get temperature event and print its value. 65 | sensors_event_t event; 66 | dht.temperature().getEvent(&event); 67 | if (isnan(event.temperature)) { 68 | Serial.println(F("Error reading temperature!")); 69 | } 70 | else { 71 | Serial.print(F("Temperature: ")); 72 | Serial.print(event.temperature); 73 | Serial.println(F("°C")); 74 | } 75 | // Get humidity event and print its value. 76 | dht.humidity().getEvent(&event); 77 | if (isnan(event.relative_humidity)) { 78 | Serial.println(F("Error reading humidity!")); 79 | } 80 | else { 81 | Serial.print(F("Humidity: ")); 82 | Serial.print(event.relative_humidity); 83 | Serial.println(F("%")); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /examples/DHTtester/DHTtester.ino: -------------------------------------------------------------------------------- 1 | // Example testing sketch for various DHT humidity/temperature sensors 2 | // Written by ladyada, public domain 3 | 4 | // REQUIRES the following Arduino libraries: 5 | // - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library 6 | // - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor 7 | 8 | #include "DHT.h" 9 | 10 | #define DHTPIN 2 // Digital pin connected to the DHT sensor 11 | // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 -- 12 | // Pin 15 can work but DHT must be disconnected during program upload. 13 | 14 | // Uncomment whatever type you're using! 15 | //#define DHTTYPE DHT11 // DHT 11 16 | #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 17 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 18 | 19 | // Connect pin 1 (on the left) of the sensor to +5V 20 | // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 21 | // to 3.3V instead of 5V! 22 | // Connect pin 2 of the sensor to whatever your DHTPIN is 23 | // Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins) 24 | // Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins) 25 | // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor 26 | 27 | // Initialize DHT sensor. 28 | // Note that older versions of this library took an optional third parameter to 29 | // tweak the timings for faster processors. This parameter is no longer needed 30 | // as the current DHT reading algorithm adjusts itself to work on faster procs. 31 | DHT dht(DHTPIN, DHTTYPE); 32 | 33 | void setup() { 34 | Serial.begin(9600); 35 | Serial.println(F("DHTxx test!")); 36 | 37 | dht.begin(); 38 | } 39 | 40 | void loop() { 41 | // Wait a few seconds between measurements. 42 | delay(2000); 43 | 44 | // Reading temperature or humidity takes about 250 milliseconds! 45 | // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 46 | float h = dht.readHumidity(); 47 | // Read temperature as Celsius (the default) 48 | float t = dht.readTemperature(); 49 | // Read temperature as Fahrenheit (isFahrenheit = true) 50 | float f = dht.readTemperature(true); 51 | 52 | // Check if any reads failed and exit early (to try again). 53 | if (isnan(h) || isnan(t) || isnan(f)) { 54 | Serial.println(F("Failed to read from DHT sensor!")); 55 | return; 56 | } 57 | 58 | // Compute heat index in Fahrenheit (the default) 59 | float hif = dht.computeHeatIndex(f, h); 60 | // Compute heat index in Celsius (isFahreheit = false) 61 | float hic = dht.computeHeatIndex(t, h, false); 62 | 63 | Serial.print(F("Humidity: ")); 64 | Serial.print(h); 65 | Serial.print(F("% Temperature: ")); 66 | Serial.print(t); 67 | Serial.print(F("°C ")); 68 | Serial.print(f); 69 | Serial.print(F("°F Heat index: ")); 70 | Serial.print(hic); 71 | Serial.print(F("°C ")); 72 | Serial.print(hif); 73 | Serial.println(F("°F")); 74 | } 75 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ########################################### 2 | # Syntax Coloring Map For DHT-sensor-library 3 | ########################################### 4 | 5 | ########################################### 6 | # Datatypes (KEYWORD1) 7 | ########################################### 8 | 9 | DHT KEYWORD1 10 | 11 | ########################################### 12 | # Methods and Functions (KEYWORD2) 13 | ########################################### 14 | 15 | begin KEYWORD2 16 | readTemperature KEYWORD2 17 | convertCtoF KEYWORD2 18 | convertFtoC KEYWORD2 19 | computeHeatIndex KEYWORD2 20 | readHumidity KEYWORD2 21 | read KEYWORD2 22 | 23 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=DHT sensor library 2 | version=1.4.6 3 | author=Adafruit 4 | maintainer=Adafruit 5 | sentence=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors 6 | paragraph=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors 7 | category=Sensors 8 | url=https://github.com/adafruit/DHT-sensor-library 9 | architectures=* 10 | depends=Adafruit Unified Sensor 11 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Adafruit Industries 2 | 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 20 | OR OTHER DEALINGS IN THE SOFTWARE. 21 | --------------------------------------------------------------------------------