Advertisement
garamycin

dht11.cpp

Jul 21st, 2012
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. //
  2. // FILE: dht11.cpp
  3. // VERSION: 0.3.2
  4. // PURPOSE: DHT11 Temperature & Humidity Sensor library for Arduino
  5. // LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
  6. //
  7. // DATASHEET: http://www.micro4you.com/files/sensor/DHT11.pdf
  8. //
  9. // HISTORY:
  10. // George Hadjikyriacou - Original version (??)
  11. // Mod by SimKard - Version 0.2 (24/11/2010)
  12. // Mod by Rob Tillaart - Version 0.3 (28/03/2011)
  13. // + added comments
  14. // + removed all non DHT11 specific code
  15. // + added references
  16. //
  17.  
  18. #include "dht11.h"
  19.  
  20. // returnvalues:
  21. // 0 : OK
  22. // -1 : checksum error
  23. // -2 : timeout
  24. int dht11::read(int pin)
  25. {
  26. // BUFFER TO RECEIVE
  27. uint8_t bits[5];
  28. uint8_t cnt = 7;
  29. uint8_t idx = 0;
  30.  
  31. // EMPTY BUFFER
  32. for (int i=0; i< 5; i++) bits[i] = 0;
  33.  
  34. // REQUEST SAMPLE
  35. pinMode(pin, OUTPUT);
  36. digitalWrite(pin, LOW);
  37. delay(18);
  38. digitalWrite(pin, HIGH);
  39. delayMicroseconds(40);
  40. pinMode(pin, INPUT);
  41.  
  42. // ACKNOWLEDGE or TIMEOUT
  43. unsigned int loopCnt = 10000;
  44. while(digitalRead(pin) == LOW)
  45. if (loopCnt-- == 0) return -2;
  46.  
  47. loopCnt = 10000;
  48. while(digitalRead(pin) == HIGH)
  49. if (loopCnt-- == 0) return -2;
  50.  
  51. // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
  52. for (int i=0; i<40; i++)
  53. {
  54. loopCnt = 10000;
  55. while(digitalRead(pin) == LOW)
  56. if (loopCnt-- == 0) return -2;
  57.  
  58. unsigned long t = micros();
  59.  
  60. loopCnt = 10000;
  61. while(digitalRead(pin) == HIGH)
  62. if (loopCnt-- == 0) return -2;
  63.  
  64. if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
  65. if (cnt == 0) // next byte?
  66. {
  67. cnt = 7; // restart at MSB
  68. idx++; // next byte!
  69. }
  70. else cnt--;
  71. }
  72.  
  73. // WRITE TO RIGHT VARS
  74. // as bits[1] and bits[3] are allways zero they are omitted in formulas.
  75. humidity = bits[0];
  76. temperature = bits[2];
  77.  
  78. uint8_t sum = bits[0] + bits[2];
  79.  
  80. if (bits[4] != sum) return -1;
  81. return 0;
  82. }
  83. //
  84. // END OF FILE
  85. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement