DHT.cpp 11 KB

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