DHT11.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // FILE: dht11.cpp
  3. // VERSION: 0.4.1
  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. // Mod by Rob Tillaart - Version 0.4 (17/03/2012)
  17. // + added 1.0 support
  18. // Mod by Rob Tillaart - Version 0.4.1 (19/05/2012)
  19. // + added error codes
  20. //
  21. #include "dht11.h"
  22. // Return values:
  23. // DHTLIB_OK
  24. // DHTLIB_ERROR_CHECKSUM
  25. // DHTLIB_ERROR_TIMEOUT
  26. int dht11::read(int pin)
  27. {
  28. // BUFFER TO RECEIVE
  29. uint8_t bits[5];
  30. uint8_t cnt = 7;
  31. uint8_t idx = 0;
  32. // EMPTY BUFFER
  33. for (int i=0; i< 5; i++) bits[i] = 0;
  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. // ACKNOWLEDGE or TIMEOUT
  42. unsigned int loopCnt = 10000;
  43. while(digitalRead(pin) == LOW)
  44. if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
  45. loopCnt = 10000;
  46. while(digitalRead(pin) == HIGH)
  47. if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
  48. // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
  49. for (int i=0; i<40; i++)
  50. {
  51. loopCnt = 10000;
  52. while(digitalRead(pin) == LOW)
  53. if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
  54. unsigned long t = micros();
  55. loopCnt = 10000;
  56. while(digitalRead(pin) == HIGH)
  57. if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
  58. if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
  59. if (cnt == 0) // next byte?
  60. {
  61. cnt = 7; // restart at MSB
  62. idx++; // next byte!
  63. }
  64. else cnt--;
  65. }
  66. // WRITE TO RIGHT VARS
  67. // as bits[1] and bits[3] are allways zero they are omitted in formulas.
  68. humidity = bits[0];
  69. temperature = bits[2];
  70. uint8_t sum = bits[0] + bits[2];
  71. if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;
  72. return DHTLIB_OK;
  73. }
  74. //
  75. // END OF FILE
  76. //