dht22.c 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //DHT library for the ESP8266, a port from the Adafruit library for the Arduino
  2. //MIT license
  3. //written by IoT Pipe
  4. #include "dht22.h"
  5. #define MIN_INTERVAL 2000
  6. #define NUM_VALID_INPUT_PINS 8
  7. const uint32_t pin_mux[NUM_VALID_INPUT_PINS] = {PERIPHS_IO_MUX_GPIO0_U,PERIPHS_IO_MUX_GPIO2_U,PERIPHS_IO_MUX_GPIO4_U,PERIPHS_IO_MUX_GPIO5_U,PERIPHS_IO_MUX_MTDI_U,PERIPHS_IO_MUX_MTCK_U,PERIPHS_IO_MUX_MTMS_U,PERIPHS_IO_MUX_MTDO_U};
  8. const uint8_t pin_num[NUM_VALID_INPUT_PINS] = {0,2,4,5,12,13,14,15};
  9. const uint8_t pin_func[NUM_VALID_INPUT_PINS] = {FUNC_GPIO0, FUNC_GPIO2,FUNC_GPIO4,FUNC_GPIO5,FUNC_GPIO12,FUNC_GPIO13,FUNC_GPIO14,FUNC_GPIO15};
  10. float ICACHE_FLASH_ATTR convertCtoF(float c) {
  11. return c * 1.8 + 32;
  12. }
  13. float ICACHE_FLASH_ATTR convertFtoC(float f) {
  14. return (f - 32) * 0.55555;
  15. }
  16. static int ICACHE_FLASH_ATTR get_index(int pin)
  17. {
  18. int i = 0;
  19. for(i = 0; i < NUM_VALID_INPUT_PINS; i++)
  20. {
  21. if(pin==pin_num[i])
  22. {
  23. return i;
  24. }
  25. }
  26. return -1;
  27. }
  28. void ICACHE_FLASH_ATTR DHT_begin(void)
  29. {
  30. LOG_DEBUG("DHT BEGIN");
  31. // set up the pins!
  32. int index = get_index(_pin);
  33. gpio_init();
  34. PIN_FUNC_SELECT(pin_mux[index],pin_func[index]);
  35. //GPIO_OUTPUT_SET(_pin,1);
  36. GPIO_DIS_OUTPUT(_pin);
  37. PIN_PULLUP_EN(pin_mux[index]);
  38. // Using this value makes sure that millis() - lastreadtime will be >= MIN_INTERVAL right away. Note that this assignment wraps around, but so will the subtraction.
  39. _lastreadtime = -MIN_INTERVAL;
  40. }
  41. static bool read() {
  42. int index = get_index(_pin);
  43. // Check if sensor was read less than two seconds ago and return early to use last reading.
  44. //This is todo. The force argument overrides this logic. We can implement in ESP8266 with a timer.
  45. uint32 current = system_get_time();
  46. if ( current - _lastreadtime < 2000000 )
  47. {
  48. LOG_DEBUG_ARGS("2 seconds is required between polls, Its only been %d (ms)",(current-_lastreadtime) / 1000);
  49. return _lastresult;
  50. }
  51. _lastreadtime=current;
  52. // Reset 40 bits of received data to zero.
  53. data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  54. // Send start signal. See DHT datasheet for full signal diagram:
  55. // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
  56. // Go into high impedence state to let pull-up raise data line level and
  57. // start the reading process.
  58. GPIO_OUTPUT_SET(_pin,1);
  59. os_delay_us(250*1000);
  60. // First set data line low for 10 milliseconds.
  61. GPIO_OUTPUT_SET(_pin,0);
  62. os_delay_us(10*1000);
  63. uint32_t cycles[80];
  64. {
  65. // Turn off interrupts temporarily because the next sections are timing critical
  66. // and we don't want any interruptions.
  67. //TODO: We've disabled GPIO interrupts, but we haven't done anything about timers
  68. ETS_GPIO_INTR_DISABLE();
  69. // End the start signal by setting data line high for 40 microseconds.
  70. GPIO_OUTPUT_SET(_pin,1);
  71. os_delay_us(40);
  72. // Now start reading the data line to get the value from the DHT sensor.
  73. GPIO_DIS_OUTPUT(_pin);
  74. PIN_PULLUP_EN(pin_mux[index]);
  75. //os_delay_us(100); // Delay a bit to let sensor pull data line low.
  76. // First expect a low signal for ~80 microseconds followed by a high signal
  77. // for ~80 microseconds again.
  78. if (expectPulse(0) == 0)
  79. {
  80. LOG_DEBUG("Timeout waiting for start signal low pulse.");
  81. _lastresult = false;
  82. return _lastresult;
  83. }
  84. if (expectPulse(1) == 0)
  85. {
  86. LOG_DEBUG("Timeout waiting for start signal high pulse.");
  87. _lastresult = false;
  88. return _lastresult;
  89. }
  90. // Now read the 40 bits sent by the sensor. Each bit is sent as a 50
  91. // microsecond low pulse followed by a variable length high pulse. If the
  92. // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds
  93. // then it's a 1. We measure the cycle count of the initial 50us low pulse
  94. // and use that to compare to the cycle count of the high pulse to determine
  95. // if the bit is a 0 (high state cycle count < low state cycle count), or a
  96. // 1 (high state cycle count > low state cycle count). Note that for speed all
  97. // the pulses are read into a array and then examined in a later step.
  98. int i = 0;
  99. for (i=0; i<80; i+=2)
  100. {
  101. cycles[i] = expectPulse(0);
  102. cycles[i+1] = expectPulse(1);
  103. }
  104. } // Timing critical code is now complete.
  105. ETS_GPIO_INTR_ENABLE();
  106. // Inspect pulses and determine which ones are 0 (high state cycle count < low
  107. // state cycle count), or 1 (high state cycle count > low state cycle count).
  108. int i = 0;
  109. for (i=0; i<40; ++i)
  110. {
  111. uint32_t lowCycles = cycles[2*i];
  112. uint32_t highCycles = cycles[2*i+1];
  113. if ((lowCycles == 0) || (highCycles == 0))
  114. {
  115. LOG_DEBUG("Timeout waiting for pulse.");
  116. _lastresult = false;
  117. return _lastresult;
  118. }
  119. data[i/8] <<= 1;
  120. // Now compare the low and high cycle times to see if the bit is a 0 or 1.
  121. if (highCycles > lowCycles)
  122. {
  123. // High cycles are greater than 50us low cycle count, must be a 1.
  124. data[i/8] |= 1;
  125. }
  126. // Else high cycles are less than (or equal to, a weird case) the 50us low
  127. // cycle count so this must be a zero. Nothing needs to be changed in the
  128. // stored data.
  129. }
  130. LOG_DEBUG_ARGS("Received: %d,%d,%d,%d,%d ?= %d",data[0],data[1],data[2],data[3],data[4],(data[0] + data[1] + data[2] + data[3]) & 0xFF );
  131. // Check we read 40 bits and that the checksum matches.
  132. if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))
  133. {
  134. _lastresult = true;
  135. float f = data[0];
  136. f *= 256;
  137. f += data[1];
  138. f *= 0.1;
  139. f = data[2] & 0x7F;
  140. f *= 256;
  141. f += data[3];
  142. f *= 0.1;
  143. if (data[2] & 0x80) {
  144. f *= -1;
  145. }
  146. return _lastresult;
  147. }
  148. else
  149. {
  150. LOG_DEBUG("Checksum failure!");
  151. _lastresult = false;
  152. return _lastresult;
  153. }
  154. }
  155. // Expect the signal line to be at the specified level for a period of time and
  156. // return a count of loop cycles spent at that level (this cycle count can be
  157. // used to compare the relative time of two pulses). If more than a millisecond
  158. // ellapses without the level changing then the call fails with a 0 response.
  159. // This is adapted from Arduino's pulseInLong function (which is only available
  160. // in the very latest IDE versions):
  161. // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
  162. uint32_t expectPulse(bool level)
  163. {
  164. uint32_t count = 0;
  165. while (GPIO_INPUT_GET(_pin) == level)
  166. {
  167. if (count++ >= _maxcycles)
  168. {
  169. LOG_DEBUG_ARGS("Max cycles reached: %d",count);
  170. return 0; // Exceeded timeout, fail.
  171. }
  172. }
  173. return count;
  174. }
  175. void DHT_init(uint8_t pin, uint8_t type, uint8_t count)
  176. {
  177. LOG_DEBUG("DHT_INIT");
  178. _pin = pin;
  179. _type = type;
  180. //_maxcycles gives thenumber of cycles in a millisecond. this is used as a timeout in other functions.
  181. //bit11~bit0 are decimal part
  182. uint32_t cal = system_rtc_clock_cali_proc();
  183. uint32_t int_part = ((cal*1000) >> 12) / 1000;// + ( (float)(((cal*1000)>>12)%1000 ) / 1000.0f);
  184. uint32_t dec_part = ((cal * 1000) >> 12) % 1000;
  185. float result = int_part + (float)dec_part/1000.0f;
  186. _maxcycles = 1000.0f / result;
  187. LOG_DEBUG_ARGS("max cycles: %d",(int)_maxcycles);
  188. }
  189. float readHumidity()
  190. {
  191. float f = -1;
  192. if (read())
  193. {
  194. switch (_type)
  195. {
  196. case DHT11:
  197. f = data[0];
  198. break;
  199. case DHT22:
  200. case DHT21:
  201. f = data[0];
  202. f *= 256;
  203. f += data[1];
  204. f *= 0.1;
  205. break;
  206. }
  207. }
  208. return f;
  209. }
  210. //boolean S == Scale. True == Fahrenheit; False == Celcius
  211. float readTemperature(bool S) {
  212. float f = -1;
  213. if (read())
  214. {
  215. switch (_type)
  216. {
  217. case DHT11:
  218. f = data[2];
  219. if(S)
  220. {
  221. f = convertCtoF(f);
  222. }
  223. break;
  224. case DHT22:
  225. case DHT21:
  226. f = data[2] & 0x7F;
  227. f *= 256;
  228. f += data[3];
  229. f *= 0.1;
  230. if (data[2] & 0x80)
  231. {
  232. f *= -1;
  233. }
  234. if(S)
  235. {
  236. f = convertCtoF(f);
  237. }
  238. break;
  239. }
  240. }
  241. return f;
  242. }