DHT.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. // based 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(isFahrenheit) {
  82. float hi = self.computeHeatIndex(self.readTemperature(isFahrenheit), self.readHumidity(), isFahrenheit);
  83. return isFahrenheit ? hi : convertFtoC(hi);
  84. }
  85. //boolean isFahrenheit: True == Fahrenheit; False == Celcius
  86. float DHT::computeHeatIndex(float temperature, floast percentHumidity, bool isFahrenheit) {
  87. // Using both Rothfusz and Steadman's equations
  88. // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
  89. float hi;
  90. if (!isFahrenheit)
  91. temperature = convertCtoF(temperature);
  92. hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094));
  93. if (hi > 79) {
  94. hi = -42.379 +
  95. 2.04901523 * temperature +
  96. 10.14333127 * percentHumidity +
  97. -0.22475541 * temperature*percentHumidity +
  98. -0.00683783 * pow(temperature, 2) +
  99. -0.05481717 * pow(percentHumidity, 2) +
  100. 0.00122874 * pow(temperature, 2) * percentHumidity +
  101. 0.00085282 * temperature*pow(percentHumidity, 2) +
  102. -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);
  103. if((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0))
  104. hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);
  105. else if((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0))
  106. hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
  107. }
  108. return isFahrenheit ? hi : convertFtoC(hi);
  109. }
  110. boolean DHT::read(bool force) {
  111. // Check if sensor was read less than two seconds ago and return early
  112. // to use last reading.
  113. uint32_t currenttime = millis();
  114. if (!force && ((currenttime - _lastreadtime) < 2000)) {
  115. return _lastresult; // return last correct measurement
  116. }
  117. _lastreadtime = currenttime;
  118. // Reset 40 bits of received data to zero.
  119. data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  120. // Send start signal. See DHT datasheet for full signal diagram:
  121. // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
  122. // Go into high impedence state to let pull-up raise data line level and
  123. // start the reading process.
  124. digitalWrite(_pin, HIGH);
  125. delay(250);
  126. // First set data line low for 20 milliseconds.
  127. pinMode(_pin, OUTPUT);
  128. digitalWrite(_pin, LOW);
  129. delay(20);
  130. uint32_t cycles[80];
  131. {
  132. // Turn off interrupts temporarily because the next sections are timing critical
  133. // and we don't want any interruptions.
  134. InterruptLock lock;
  135. // End the start signal by setting data line high for 40 microseconds.
  136. digitalWrite(_pin, HIGH);
  137. delayMicroseconds(40);
  138. // Now start reading the data line to get the value from the DHT sensor.
  139. pinMode(_pin, INPUT_PULLUP);
  140. delayMicroseconds(10); // Delay a bit to let sensor pull data line low.
  141. // First expect a low signal for ~80 microseconds followed by a high signal
  142. // for ~80 microseconds again.
  143. if (expectPulse(LOW) == 0) {
  144. DEBUG_PRINTLN(F("Timeout waiting for start signal low pulse."));
  145. _lastresult = false;
  146. return _lastresult;
  147. }
  148. if (expectPulse(HIGH) == 0) {
  149. DEBUG_PRINTLN(F("Timeout waiting for start signal high pulse."));
  150. _lastresult = false;
  151. return _lastresult;
  152. }
  153. // Now read the 40 bits sent by the sensor. Each bit is sent as a 50
  154. // microsecond low pulse followed by a variable length high pulse. If the
  155. // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds
  156. // then it's a 1. We measure the cycle count of the initial 50us low pulse
  157. // and use that to compare to the cycle count of the high pulse to determine
  158. // if the bit is a 0 (high state cycle count < low state cycle count), or a
  159. // 1 (high state cycle count > low state cycle count). Note that for speed all
  160. // the pulses are read into a array and then examined in a later step.
  161. for (int i=0; i<80; i+=2) {
  162. cycles[i] = expectPulse(LOW);
  163. cycles[i+1] = expectPulse(HIGH);
  164. }
  165. } // Timing critical code is now complete.
  166. // Inspect pulses and determine which ones are 0 (high state cycle count < low
  167. // state cycle count), or 1 (high state cycle count > low state cycle count).
  168. for (int i=0; i<40; ++i) {
  169. uint32_t lowCycles = cycles[2*i];
  170. uint32_t highCycles = cycles[2*i+1];
  171. if ((lowCycles == 0) || (highCycles == 0)) {
  172. DEBUG_PRINTLN(F("Timeout waiting for pulse."));
  173. _lastresult = false;
  174. return _lastresult;
  175. }
  176. data[i/8] <<= 1;
  177. // Now compare the low and high cycle times to see if the bit is a 0 or 1.
  178. if (highCycles > lowCycles) {
  179. // High cycles are greater than 50us low cycle count, must be a 1.
  180. data[i/8] |= 1;
  181. }
  182. // Else high cycles are less than (or equal to, a weird case) the 50us low
  183. // cycle count so this must be a zero. Nothing needs to be changed in the
  184. // stored data.
  185. }
  186. DEBUG_PRINTLN(F("Received:"));
  187. DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(", "));
  188. DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(", "));
  189. DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(", "));
  190. DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(", "));
  191. DEBUG_PRINT(data[4], HEX); DEBUG_PRINT(F(" =? "));
  192. DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX);
  193. // Check we read 40 bits and that the checksum matches.
  194. if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
  195. _lastresult = true;
  196. return _lastresult;
  197. }
  198. else {
  199. DEBUG_PRINTLN(F("Checksum failure!"));
  200. _lastresult = false;
  201. return _lastresult;
  202. }
  203. }
  204. // Expect the signal line to be at the specified level for a period of time and
  205. // return a count of loop cycles spent at that level (this cycle count can be
  206. // used to compare the relative time of two pulses). If more than a millisecond
  207. // ellapses without the level changing then the call fails with a 0 response.
  208. // This is adapted from Arduino's pulseInLong function (which is only available
  209. // in the very latest IDE versions):
  210. // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
  211. uint32_t DHT::expectPulse(bool level) {
  212. uint32_t count = 0;
  213. // On AVR platforms use direct GPIO port access as it's much faster and better
  214. // for catching pulses that are 10's of microseconds in length:
  215. #ifdef __AVR
  216. uint8_t portState = level ? _bit : 0;
  217. while ((*portInputRegister(_port) & _bit) == portState) {
  218. if (count++ >= _maxcycles) {
  219. return 0; // Exceeded timeout, fail.
  220. }
  221. }
  222. // Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266
  223. // right now, perhaps bugs in direct port access functions?).
  224. #else
  225. while (digitalRead(_pin) == level) {
  226. if (count++ >= _maxcycles) {
  227. return 0; // Exceeded timeout, fail.
  228. }
  229. }
  230. #endif
  231. return count;
  232. }