DHT.cpp 9.1 KB

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