Repository navigation
Expand file tree
/
Copy pathDHT22.cpp
More file actions
120 lines (90 loc) · 2.48 KB
/
Copy pathDHT22.cpp
File metadata and controls
120 lines (90 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/******************************************************
SENSOR LIBRARY:
Written by Enrico Formenti.
BSD license, check license.txt for more information
All text above must be included in any redistribution.
******************************************************/
/* Sensor library
DHT22.CPP: class methods for DHT22 class
written by Enrico Formenti
*/
/**
\file DHT22.cpp
\brief Implementation of DHT22 class.
\author Enrico Formenti
\version 0.1
\date 2012-2013
\warning This software is provided "as is". The author is
not responsible for any damage of any kind caused by this
software. Use it at your own risk.
\copyright BSD license. See license.txt for more details.
All text above must be included in any redistribution.
*/
#include "DHT22.h"
void DHT22::begin(void) {
uint8_t i;
firstreading = true;
// clear data bits
for(i=0;i<40;i++)
_data[i]=0;
// set up the pins!
pinMode(_pin, INPUT);
digitalWrite(_pin, HIGH);
_lastreadtime = 0;
}
void DHT22::read(void) {
uint8_t laststate = HIGH;
uint8_t counter;
uint8_t i;
unsigned long currenttime;
setError(ERROR_NONE);
currenttime = millis();
if (currenttime < _lastreadtime) // ie there was a rollover
_lastreadtime = 0;
if (!firstreading && ((currenttime - _lastreadtime) < 2000))
return; // return last correct measurement
firstreading = false;
_lastreadtime = millis();
// pull the pin high and wait 250 milliseconds
digitalWrite(_pin, HIGH);
delay(250);
// now pull it low for ~20 milliseconds
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delay(20);
cli();
digitalWrite(_pin, HIGH);
delayMicroseconds(40);
pinMode(_pin, INPUT);
// read in bits
for ( i=0; i<40; i++) {
// we should check how much time exactly it is lost here
for (counter=0; (counter<255)&&(digitalRead(_pin) == laststate); counter++)
delayMicroseconds(1);
laststate = digitalRead(_pin);
if (counter == 255) {
Error::setError(ERROR_TIME_OUT);
return;
}
if (counter > 6) // this value should be tried out !!!!
_data[i/5] |= (1 << (i%8));
}
sei();
// check we read 40 bits and that the checksum matches
if( counter != 40 ) {
Error::setError(ERROR_READ_FAILURE);
return;
}
if( _data[4] != ( (_data[0] + _data[1] + _data[2] + _data[3]) & 0xFF) ) {
Error::setError(ERROR_INVALID_CRC);
return;
}
}
float DHT22::getHumidity(void) {
read();
return ((_data[0]<<8)|_data[1])/10;
}
float DHT22::getTemperature(void) {
read();
return ((_data[2]<<8)|_data[3])/10;
}