Merge branch 'master' of mjesec.ffzg.hr:/git/Arduino
[Arduino] / libraries / DHT11 / dht11.cpp
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
22 #include "dht11.h"
23
24 // Return values:
25 // DHTLIB_OK
26 // DHTLIB_ERROR_CHECKSUM
27 // DHTLIB_ERROR_TIMEOUT
28 int dht11::read(int pin)
29 {
30         // BUFFER TO RECEIVE
31         uint8_t bits[5];
32         uint8_t cnt = 7;
33         uint8_t idx = 0;
34
35         // EMPTY BUFFER
36         for (int i=0; i< 5; i++) bits[i] = 0;
37
38         // REQUEST SAMPLE
39         pinMode(pin, OUTPUT);
40         digitalWrite(pin, LOW);
41         delay(18);
42         digitalWrite(pin, HIGH);
43         delayMicroseconds(40);
44         pinMode(pin, INPUT);
45
46         // ACKNOWLEDGE or TIMEOUT
47         unsigned int loopCnt = 10000;
48         while(digitalRead(pin) == LOW)
49                 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
50
51         loopCnt = 10000;
52         while(digitalRead(pin) == HIGH)
53                 if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
54
55         // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
56         for (int i=0; i<40; i++)
57         {
58                 loopCnt = 10000;
59                 while(digitalRead(pin) == LOW)
60                         if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
61
62                 unsigned long t = micros();
63
64                 loopCnt = 10000;
65                 while(digitalRead(pin) == HIGH)
66                         if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
67
68                 if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
69                 if (cnt == 0)   // next byte?
70                 {
71                         cnt = 7;    // restart at MSB
72                         idx++;      // next byte!
73                 }
74                 else cnt--;
75         }
76
77         // WRITE TO RIGHT VARS
78         // as bits[1] and bits[3] are allways zero they are omitted in formulas.
79         humidity    = bits[0]; 
80         temperature = bits[2]; 
81
82         uint8_t sum = bits[0] + bits[2];  
83
84         if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;
85         return DHTLIB_OK;
86 }
87 //
88 // END OF FILE
89 //