4 // PURPOSE: DHT11 Temperature & Humidity Sensor library for Arduino
5 // LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
7 // DATASHEET: http://www.micro4you.com/files/sensor/DHT11.pdf
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)
14 // + removed all non DHT11 specific code
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
26 // DHTLIB_ERROR_CHECKSUM
27 // DHTLIB_ERROR_TIMEOUT
28 int dht11::read(int pin)
36 for (int i=0; i< 5; i++) bits[i] = 0;
40 digitalWrite(pin, LOW);
42 digitalWrite(pin, HIGH);
43 delayMicroseconds(40);
46 // ACKNOWLEDGE or TIMEOUT
47 unsigned int loopCnt = 10000;
48 while(digitalRead(pin) == LOW)
49 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
52 while(digitalRead(pin) == HIGH)
53 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
55 // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
56 for (int i=0; i<40; i++)
59 while(digitalRead(pin) == LOW)
60 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
62 unsigned long t = micros();
65 while(digitalRead(pin) == HIGH)
66 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
68 if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
69 if (cnt == 0) // next byte?
71 cnt = 7; // restart at MSB
77 // WRITE TO RIGHT VARS
78 // as bits[1] and bits[3] are allways zero they are omitted in formulas.
80 temperature = bits[2];
82 uint8_t sum = bits[0] + bits[2];
84 if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;