Skip to content

Instantly share code, notes, and snippets.

@freekode
Created May 19, 2013 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freekode/5608158 to your computer and use it in GitHub Desktop.
Save freekode/5608158 to your computer and use it in GitHub Desktop.
#ifndef DHT22_h
#define DHT22_h
#define DHTLIB_OK 0
#define DHTLIB_ERROR_CHECKSUM -1
#define DHTLIB_ERROR_TIMEOUT -2
#define DHTLIB_INVALID_VALUE -999
#define TIMEOUT 10000
class ClassDHT22 {
public:
int temperature();
unsigned int humidity();
uint8_t bits[5]; // buffer to receive data
int read(uint8_t pin);
};
ClassDHT22 DHT22 = ClassDHT22();
int ClassDHT22::temperature() {
return word(bits[2]&0x7F, bits[3]);
}
unsigned int ClassDHT22::humidity() {
return word(bits[0], bits[1]);
}
int ClassDHT22::read(uint8_t pin) {
uint8_t cnt = 7;
uint8_t idx = 0;
for (int i=0; i< 5; i++) bits[i] = 0;
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(20);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// GET ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = TIMEOUT;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
loopCnt = TIMEOUT;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
// READ THE OUTPUT - 40 BITS => 5 BYTES
for (int i=0; i<40; i++) {
loopCnt = TIMEOUT;
while(digitalRead(pin) == LOW) {
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
}
unsigned long t = micros();
loopCnt = TIMEOUT;
while(digitalRead(pin) == HIGH) {
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
}
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) {
cnt = 7;
idx++;
}
else cnt--;
}
return DHTLIB_OK;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment