DHT.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /* DHT library
  2. MIT license
  3. written by Adafruit Industries
  4. */
  5. #include "DHT.h"
  6. #define MIN_INTERVAL 2000
  7. DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
  8. _pin = pin;
  9. _type = type;
  10. #ifdef __AVR
  11. _bit = digitalPinToBitMask(pin);
  12. _port = digitalPinToPort(pin);
  13. #endif
  14. _maxcycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for
  15. // reading pulses from DHT sensor.
  16. // Note that count is now ignored as the DHT reading algorithm adjusts itself
  17. // basd on the speed of the processor.
  18. }
  19. void DHT::begin(void) {
  20. // set up the pins!
  21. pinMode(_pin, INPUT_PULLUP);
  22. // Using this value makes sure that millis() - lastreadtime will be
  23. // >= MIN_INTERVAL right away. Note that this assignment wraps around,
  24. // but so will the subtraction.
  25. _lastreadtime = -MIN_INTERVAL;
  26. DEBUG_PRINT("Max clock cycles: "); DEBUG_PRINTLN(_maxcycles, DEC);
  27. }
  28. //boolean S == Scale. True == Fahrenheit; False == Celcius
  29. float DHT::readTemperature(bool S, bool force) {
  30. float f = NAN;
  31. if (read(force)) {
  32. switch (_type) {
  33. case DHT11:
  34. f = data[2];
  35. if(S) {
  36. f = convertCtoF(f);
  37. }
  38. break;
  39. case DHT22:
  40. case DHT21:
  41. f = data[2] & 0x7F;
  42. f *= 256;
  43. f += data[3];
  44. f *= 0.1;
  45. if (data[2] & 0x80) {
  46. f *= -1;
  47. }
  48. if(S) {
  49. f = convertCtoF(f);
  50. }
  51. break;
  52. }
  53. }
  54. return f;
  55. }
  56. float DHT::convertCtoF(float c) {
  57. return c * 1.8 + 32;
  58. }
  59. float DHT::convertFtoC(float f) {
  60. return (f - 32) * 0.55555;
  61. }
  62. float DHT::readHumidity(bool force) {
  63. float f = NAN;
  64. if (read()) {
  65. switch (_type) {
  66. case DHT11:
  67. f = data[0];
  68. break;
  69. case DHT22:
  70. case DHT21:
  71. f = data[0];
  72. f *= 256;
  73. f += data[1];
  74. f *= 0.1;
  75. break;
  76. }
  77. }
  78. return f;
  79. }
  80. //boolean isFahrenheit: True == Fahrenheit; False == Celcius
  81. float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit) {
  82. // Using both Rothfusz and Steadman's equations
  83. // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
  84. float hi;
  85. if (!isFahrenheit)
  86. temperature = convertCtoF(temperature);
  87. hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094));
  88. if (hi > 79) {
  89. hi = -42.379 +
  90. 2.04901523 * temperature +
  91. 10.14333127 * percentHumidity +
  92. -0.22475541 * temperature*percentHumidity +
  93. -0.00683783 * pow(temperature, 2) +
  94. -0.05481717 * pow(percentHumidity, 2) +
  95. 0.00122874 * pow(temperature, 2) * percentHumidity +
  96. 0.00085282 * temperature*pow(percentHumidity, 2) +
  97. -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);
  98. if((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0))
  99. hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);
  100. else if((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0))
  101. hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
  102. }
  103. return isFahrenheit ? hi : convertFtoC(hi);
  104. }
  105. boolean DHT::read(bool force) {
  106. // Check if sensor was read less than two seconds ago and return early
  107. // to use last reading.
  108. uint32_t currenttime = millis();
  109. if (!force && ((currenttime - _lastreadtime) < 2000)) {
  110. return _lastresult; // return last correct measurement
  111. }
  112. _lastreadtime = currenttime;
  113. // Reset 40 bits of received data to zero.
  114. data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  115. // Send start signal. See DHT datasheet for full signal diagram:
  116. // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
  117. // Go into high impedence state to let pull-up raise data line level and
  118. // start the reading process.
  119. digitalWrite(_pin, HIGH);
  120. delay(250);
  121. // First set data line low for 20 milliseconds.
  122. pinMode(_pin, OUTPUT);
  123. digitalWrite(_pin, LOW);
  124. delay(20);
  125. uint32_t cycles[80];
  126. {
  127. // Turn off interrupts temporarily because the next sections are timing critical
  128. // and we don't want any interruptions.
  129. InterruptLock lock;
  130. // End the start signal by setting data line high for 40 microseconds.
  131. digitalWrite(_pin, HIGH);
  132. delayMicroseconds(40);
  133. // Now start reading the data line to get the value from the DHT sensor.
  134. pinMode(_pin, INPUT_PULLUP);
  135. delayMicroseconds(10); // Delay a bit to let sensor pull data line low.
  136. // First expect a low signal for ~80 microseconds followed by a high signal
  137. // for ~80 microseconds again.
  138. if (expectPulse(LOW) == 0) {
  139. DEBUG_PRINTLN(F("Timeout waiting for start signal low pulse."));
  140. _lastresult = false;
  141. return _lastresult;
  142. }
  143. if (expectPulse(HIGH) == 0) {
  144. DEBUG_PRINTLN(F("Timeout waiting for start signal high pulse."));
  145. _lastresult = false;
  146. return _lastresult;
  147. }
  148. // Now read the 40 bits sent by the sensor. Each bit is sent as a 50
  149. // microsecond low pulse followed by a variable length high pulse. If the
  150. // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds
  151. // then it's a 1. We measure the cycle count of the initial 50us low pulse
  152. // and use that to compare to the cycle count of the high pulse to determine
  153. // if the bit is a 0 (high state cycle count < low state cycle count), or a
  154. // 1 (high state cycle count > low state cycle count). Note that for speed all
  155. // the pulses are read into a array and then examined in a later step.
  156. for (int i=0; i<80; i+=2) {
  157. cycles[i] = expectPulse(LOW);
  158. cycles[i+1] = expectPulse(HIGH);
  159. }
  160. } // Timing critical code is now complete.
  161. // Inspect pulses and determine which ones are 0 (high state cycle count < low
  162. // state cycle count), or 1 (high state cycle count > low state cycle count).
  163. for (int i=0; i<40; ++i) {
  164. uint32_t lowCycles = cycles[2*i];
  165. uint32_t highCycles = cycles[2*i+1];
  166. if ((lowCycles == 0) || (highCycles == 0)) {
  167. DEBUG_PRINTLN(F("Timeout waiting for pulse."));
  168. _lastresult = false;
  169. return _lastresult;
  170. }
  171. data[i/8] <<= 1;
  172. // Now compare the low and high cycle times to see if the bit is a 0 or 1.
  173. if (highCycles > lowCycles) {
  174. // High cycles are greater than 50us low cycle count, must be a 1.
  175. data[i/8] |= 1;
  176. }
  177. // Else high cycles are less than (or equal to, a weird case) the 50us low
  178. // cycle count so this must be a zero. Nothing needs to be changed in the
  179. // stored data.
  180. }
  181. DEBUG_PRINTLN(F("Received:"));
  182. DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(", "));
  183. DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(", "));
  184. DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(", "));
  185. DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(", "));
  186. DEBUG_PRINT(data[4], HEX); DEBUG_PRINT(F(" =? "));
  187. DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX);
  188. // Check we read 40 bits and that the checksum matches.
  189. if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
  190. _lastresult = true;
  191. return _lastresult;
  192. }
  193. else {
  194. DEBUG_PRINTLN(F("Checksum failure!"));
  195. _lastresult = false;
  196. return _lastresult;
  197. }
  198. }
  199. // Expect the signal line to be at the specified level for a period of time and
  200. // return a count of loop cycles spent at that level (this cycle count can be
  201. // used to compare the relative time of two pulses). If more than a millisecond
  202. // ellapses without the level changing then the call fails with a 0 response.
  203. // This is adapted from Arduino's pulseInLong function (which is only available
  204. // in the very latest IDE versions):
  205. // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
  206. uint32_t DHT::expectPulse(bool level) {
  207. uint32_t count = 0;
  208. // On AVR platforms use direct GPIO port access as it's much faster and better
  209. // for catching pulses that are 10's of microseconds in length:
  210. #ifdef __AVR
  211. uint8_t portState = level ? _bit : 0;
  212. while ((*portInputRegister(_port) & _bit) == portState) {
  213. if (count++ >= _maxcycles) {
  214. return 0; // Exceeded timeout, fail.
  215. }
  216. }
  217. // Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266
  218. // right now, perhaps bugs in direct port access functions?).
  219. #else
  220. while (digitalRead(_pin) == level) {
  221. if (count++ >= _maxcycles) {
  222. return 0; // Exceeded timeout, fail.
  223. }
  224. }
  225. #endif
  226. return count;
  227. }