DHT.cpp 12 KB

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