Skip to content

Instantly share code, notes, and snippets.

@sorz
Created July 19, 2013 15:26
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 sorz/6039982 to your computer and use it in GitHub Desktop.
Save sorz/6039982 to your computer and use it in GitHub Desktop.
DHT22 on Arduino. Send temperature and humidity via serial.
/*
* Author: @xierch
* License: MIT
* Known Issues: can't throw timeout exception if DHT22 broken.
*/
#define DHT22_PIN 2
void setup() {
pinMode(DHT22_PIN, INPUT_PULLUP);
Serial.begin(115200, SERIAL_8E1);
}
void loop() {
if (Serial.available() > 0) {
byte in = Serial.read();
if (in == 1) {
float temp, humi;
if (!getTempHumi(&temp, &humi)) {
temp = 255;
humi = 255;
}
Serial.write((byte *) &temp, 4);
Serial.write((byte *) &humi, 4);
}
}
}
byte _getbyte() {
byte recv = 0;
for (int i=7; i>=0; i--) {
while (!digitalRead(DHT22_PIN));
delayMicroseconds(50); // 0: 26~28us; 1: 70us high.
recv |= digitalRead(DHT22_PIN) << i;
while (digitalRead(DHT22_PIN));
}
return recv;
}
float _decode_float(byte high, byte low) {
if (high < 128) {
return (((word) high) << 8 | low) / 10.0;
} else {
return (((word) high - 128) << 8 | low) / -10.0;
}
}
boolean getTempHumi(float *temp, float *humi) {
// Wake up IC
pinMode(DHT22_PIN, OUTPUT);
digitalWrite(DHT22_PIN, LOW);
delay(18);
pinMode(DHT22_PIN, INPUT_PULLUP);
delayMicroseconds(30); // pullup 20~40us
// Receiving
digitalRead(DHT22_PIN);
delayMicroseconds(50); // low 80us
while(!digitalRead(DHT22_PIN));
delayMicroseconds(50); // high 80us
while(digitalRead(DHT22_PIN));
byte b[4];
// Calculate checksum
byte sum = 0;
for (int i=0; i<4; i++) {
b[i] = _getbyte();
sum += b[i];
}
if (sum != _getbyte()) return false;
// Decoding to float
*humi = _decode_float(b[0], b[1]);
*temp = _decode_float(b[2], b[3]);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment