DHT.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. #include "DHT.h"
  26. #define MIN_INTERVAL 2000 /**< min interval value */
  27. #define TIMEOUT \
  28. UINT32_MAX /**< Used programmatically for timeout. \
  29. Not a timeout duration. Type: uint32_t. */
  30. /*!
  31. * @brief Instantiates a new DHT class
  32. * @param pin
  33. * pin number that sensor is connected
  34. * @param type
  35. * type of sensor
  36. * @param count
  37. * number of sensors
  38. */
  39. DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
  40. (void)count; // Workaround to avoid compiler warning.
  41. _pin = pin;
  42. _type = type;
  43. #ifdef __AVR
  44. _bit = digitalPinToBitMask(pin);
  45. _port = digitalPinToPort(pin);
  46. #endif
  47. _maxcycles =
  48. microsecondsToClockCycles(1000); // 1 millisecond timeout for
  49. // reading pulses from DHT sensor.
  50. // Note that count is now ignored as the DHT reading algorithm adjusts itself
  51. // based on the speed of the processor.
  52. }
  53. /*!
  54. * @brief Setup sensor pins and set pull timings
  55. * @param usec
  56. * Optionally pass pull-up time (in microseconds) before DHT reading
  57. *starts. Default is 55 (see function declaration in DHT.h).
  58. */
  59. void DHT::begin(uint8_t usec) {
  60. // set up the pins!
  61. pinMode(_pin, INPUT_PULLUP);
  62. // Using this value makes sure that millis() - lastreadtime will be
  63. // >= MIN_INTERVAL right away. Note that this assignment wraps around,
  64. // but so will the subtraction.
  65. _lastreadtime = millis() - MIN_INTERVAL;
  66. DEBUG_PRINT("DHT max clock cycles: ");
  67. DEBUG_PRINTLN(_maxcycles, DEC);
  68. pullTime = usec;
  69. }
  70. /*!
  71. * @brief Read temperature
  72. * @param S
  73. * Scale. Boolean value:
  74. * - true = Fahrenheit
  75. * - false = Celcius
  76. * @param force
  77. * true if in force mode
  78. * @return Temperature value in selected scale
  79. */
  80. float DHT::readTemperature(bool S, bool force) {
  81. float f = NAN;
  82. if (read(force)) {
  83. switch (_type) {
  84. case DHT11:
  85. f = data[2];
  86. if (data[3] & 0x80) {
  87. f = -1 - f;
  88. }
  89. f += (data[3] & 0x0f) * 0.1;
  90. if (S) {
  91. f = convertCtoF(f);
  92. }
  93. break;
  94. case DHT12:
  95. f = data[2];
  96. f += (data[3] & 0x0f) * 0.1;
  97. if (data[2] & 0x80) {
  98. f *= -1;
  99. }
  100. if (S) {
  101. f = convertCtoF(f);
  102. }
  103. break;
  104. case DHT22:
  105. case DHT21:
  106. f = ((word)(data[2] & 0x7F)) << 8 | data[3];
  107. f *= 0.1;
  108. if (data[2] & 0x80) {
  109. f *= -1;
  110. }
  111. if (S) {
  112. f = convertCtoF(f);
  113. }
  114. break;
  115. }
  116. }
  117. return f;
  118. }
  119. /*!
  120. * @brief Converts Celcius to Fahrenheit
  121. * @param c
  122. * value in Celcius
  123. * @return float value in Fahrenheit
  124. */
  125. float DHT::convertCtoF(float c) {
  126. return c * 1.8 + 32;
  127. }
  128. /*!
  129. * @brief Converts Fahrenheit to Celcius
  130. * @param f
  131. * value in Fahrenheit
  132. * @return float value in Celcius
  133. */
  134. float DHT::convertFtoC(float f) {
  135. return (f - 32) * 0.55555;
  136. }
  137. /*!
  138. * @brief Read Humidity
  139. * @param force
  140. * force read mode
  141. * @return float value - humidity in percent
  142. */
  143. float DHT::readHumidity(bool force) {
  144. float f = NAN;
  145. if (read(force)) {
  146. switch (_type) {
  147. case DHT11:
  148. case DHT12:
  149. f = data[0] + data[1] * 0.1;
  150. break;
  151. case DHT22:
  152. case DHT21:
  153. f = ((word)data[0]) << 8 | data[1];
  154. f *= 0.1;
  155. break;
  156. }
  157. }
  158. return f;
  159. }
  160. /*!
  161. * @brief Compute Heat Index
  162. * Simplified version that reads temp and humidity from sensor
  163. * @param isFahrenheit
  164. * true if fahrenheit, false if celcius
  165. *(default true)
  166. * @return float heat index
  167. */
  168. float DHT::computeHeatIndex(bool isFahrenheit) {
  169. float hi = computeHeatIndex(readTemperature(isFahrenheit), readHumidity(),
  170. isFahrenheit);
  171. return hi;
  172. }
  173. /*!
  174. * @brief Compute Heat Index
  175. * Using both Rothfusz and Steadman's equations
  176. * (http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml)
  177. * @param temperature
  178. * temperature in selected scale
  179. * @param percentHumidity
  180. * humidity in percent
  181. * @param isFahrenheit
  182. * true if fahrenheit, false if celcius
  183. * @return float heat index
  184. */
  185. float DHT::computeHeatIndex(float temperature, float percentHumidity,
  186. bool isFahrenheit) {
  187. float hi;
  188. if (!isFahrenheit)
  189. temperature = convertCtoF(temperature);
  190. hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) +
  191. (percentHumidity * 0.094));
  192. if (hi > 79) {
  193. hi = -42.379 + 2.04901523 * temperature + 10.14333127 * percentHumidity +
  194. -0.22475541 * temperature * percentHumidity +
  195. -0.00683783 * pow(temperature, 2) +
  196. -0.05481717 * pow(percentHumidity, 2) +
  197. 0.00122874 * pow(temperature, 2) * percentHumidity +
  198. 0.00085282 * temperature * pow(percentHumidity, 2) +
  199. -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);
  200. if ((percentHumidity < 13) && (temperature >= 80.0) &&
  201. (temperature <= 112.0))
  202. hi -= ((13.0 - percentHumidity) * 0.25) *
  203. sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);
  204. else if ((percentHumidity > 85.0) && (temperature >= 80.0) &&
  205. (temperature <= 87.0))
  206. hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
  207. }
  208. return isFahrenheit ? hi : convertFtoC(hi);
  209. }
  210. /*!
  211. * @brief Read value from sensor or return last one from less than two
  212. *seconds.
  213. * @param force
  214. * true if using force mode
  215. * @return float value
  216. */
  217. bool DHT::read(bool force) {
  218. // Check if sensor was read less than two seconds ago and return early
  219. // to use last reading.
  220. uint32_t currenttime = millis();
  221. if (!force && ((currenttime - _lastreadtime) < MIN_INTERVAL)) {
  222. return _lastresult; // return last correct measurement
  223. }
  224. _lastreadtime = currenttime;
  225. // Reset 40 bits of received data to zero.
  226. data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  227. #if defined(ESP8266)
  228. yield(); // Handle WiFi / reset software watchdog
  229. #endif
  230. // Send start signal. See DHT datasheet for full signal diagram:
  231. // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
  232. // Go into high impedence state to let pull-up raise data line level and
  233. // start the reading process.
  234. pinMode(_pin, INPUT_PULLUP);
  235. delay(1);
  236. // First set data line low for a period according to sensor type
  237. pinMode(_pin, OUTPUT);
  238. digitalWrite(_pin, LOW);
  239. switch (_type) {
  240. case DHT22:
  241. case DHT21:
  242. delayMicroseconds(1100); // data sheet says "at least 1ms"
  243. break;
  244. case DHT11:
  245. default:
  246. delay(20); // data sheet says at least 18ms, 20ms just to be safe
  247. break;
  248. }
  249. uint32_t cycles[80];
  250. {
  251. // End the start signal by setting data line high for 40 microseconds.
  252. pinMode(_pin, INPUT_PULLUP);
  253. // Delay a moment to let sensor pull data line low.
  254. delayMicroseconds(pullTime);
  255. // Now start reading the data line to get the value from the DHT sensor.
  256. // Turn off interrupts temporarily because the next sections
  257. // are timing critical and we don't want any interruptions.
  258. InterruptLock lock;
  259. // First expect a low signal for ~80 microseconds followed by a high signal
  260. // for ~80 microseconds again.
  261. if (expectPulse(LOW) == TIMEOUT) {
  262. DEBUG_PRINTLN(F("DHT timeout waiting for start signal low pulse."));
  263. _lastresult = false;
  264. return _lastresult;
  265. }
  266. if (expectPulse(HIGH) == TIMEOUT) {
  267. DEBUG_PRINTLN(F("DHT timeout waiting for start signal high pulse."));
  268. _lastresult = false;
  269. return _lastresult;
  270. }
  271. // Now read the 40 bits sent by the sensor. Each bit is sent as a 50
  272. // microsecond low pulse followed by a variable length high pulse. If the
  273. // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds
  274. // then it's a 1. We measure the cycle count of the initial 50us low pulse
  275. // and use that to compare to the cycle count of the high pulse to determine
  276. // if the bit is a 0 (high state cycle count < low state cycle count), or a
  277. // 1 (high state cycle count > low state cycle count). Note that for speed
  278. // all the pulses are read into a array and then examined in a later step.
  279. for (int i = 0; i < 80; i += 2) {
  280. cycles[i] = expectPulse(LOW);
  281. cycles[i + 1] = expectPulse(HIGH);
  282. }
  283. } // Timing critical code is now complete.
  284. // Inspect pulses and determine which ones are 0 (high state cycle count < low
  285. // state cycle count), or 1 (high state cycle count > low state cycle count).
  286. for (int i = 0; i < 40; ++i) {
  287. uint32_t lowCycles = cycles[2 * i];
  288. uint32_t highCycles = cycles[2 * i + 1];
  289. if ((lowCycles == TIMEOUT) || (highCycles == TIMEOUT)) {
  290. DEBUG_PRINTLN(F("DHT timeout waiting for pulse."));
  291. _lastresult = false;
  292. return _lastresult;
  293. }
  294. data[i / 8] <<= 1;
  295. // Now compare the low and high cycle times to see if the bit is a 0 or 1.
  296. if (highCycles > lowCycles) {
  297. // High cycles are greater than 50us low cycle count, must be a 1.
  298. data[i / 8] |= 1;
  299. }
  300. // Else high cycles are less than (or equal to, a weird case) the 50us low
  301. // cycle count so this must be a zero. Nothing needs to be changed in the
  302. // stored data.
  303. }
  304. DEBUG_PRINTLN(F("Received from DHT:"));
  305. DEBUG_PRINT(data[0], HEX);
  306. DEBUG_PRINT(F(", "));
  307. DEBUG_PRINT(data[1], HEX);
  308. DEBUG_PRINT(F(", "));
  309. DEBUG_PRINT(data[2], HEX);
  310. DEBUG_PRINT(F(", "));
  311. DEBUG_PRINT(data[3], HEX);
  312. DEBUG_PRINT(F(", "));
  313. DEBUG_PRINT(data[4], HEX);
  314. DEBUG_PRINT(F(" =? "));
  315. DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX);
  316. // Check we read 40 bits and that the checksum matches.
  317. if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
  318. _lastresult = true;
  319. return _lastresult;
  320. } else {
  321. DEBUG_PRINTLN(F("DHT checksum failure!"));
  322. _lastresult = false;
  323. return _lastresult;
  324. }
  325. }
  326. // Expect the signal line to be at the specified level for a period of time and
  327. // return a count of loop cycles spent at that level (this cycle count can be
  328. // used to compare the relative time of two pulses). If more than a millisecond
  329. // ellapses without the level changing then the call fails with a 0 response.
  330. // This is adapted from Arduino's pulseInLong function (which is only available
  331. // in the very latest IDE versions):
  332. // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
  333. uint32_t DHT::expectPulse(bool level) {
  334. // F_CPU is not be known at compile time on platforms such as STM32F103.
  335. // The preprocessor seems to evaluate it to zero in that case.
  336. #if (F_CPU > 16000000L) || (F_CPU == 0L)
  337. uint32_t count = 0;
  338. #else
  339. uint16_t count = 0; // To work fast enough on slower AVR boards
  340. #endif
  341. // On AVR platforms use direct GPIO port access as it's much faster and better
  342. // for catching pulses that are 10's of microseconds in length:
  343. #ifdef __AVR
  344. uint8_t portState = level ? _bit : 0;
  345. while ((*portInputRegister(_port) & _bit) == portState) {
  346. if (count++ >= _maxcycles) {
  347. return TIMEOUT; // Exceeded timeout, fail.
  348. }
  349. }
  350. // Otherwise fall back to using digitalRead (this seems to be necessary on
  351. // ESP8266 right now, perhaps bugs in direct port access functions?).
  352. #else
  353. while (digitalRead(_pin) == level) {
  354. if (count++ >= _maxcycles) {
  355. return TIMEOUT; // Exceeded timeout, fail.
  356. }
  357. }
  358. #endif
  359. return count;
  360. }