DHT.cpp 12 KB

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