Created
May 11, 2013 18:33
-
-
Save sorz/5560907 to your computer and use it in GitHub Desktop.
DHT11 on Arduino. Send temperature and humidity by serial.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define DHT11_PIN 2 | |
void setup() { | |
pinMode(DHT11_PIN, INPUT_PULLUP); | |
Serial.begin(115200, SERIAL_8E1); | |
} | |
void loop() { | |
if (Serial.available() > 0) { | |
byte in = Serial.read(); | |
if (in == 1) { | |
byte temp, humi; | |
if (!getTempHumi(&temp, &humi)) { | |
temp = 255; | |
humi = 255; | |
} | |
Serial.write(temp); | |
Serial.write(humi); | |
} | |
} | |
byte _getbyte() { | |
byte recv = 0; | |
for (int i=7; i>=0; i--) { | |
while (!digitalRead(DHT11_PIN)); | |
delayMicroseconds(50); // 0: 26~28us; 1: 70us high. | |
recv |= digitalRead(DHT11_PIN) << i; | |
while (digitalRead(DHT11_PIN)); | |
} | |
return recv; | |
} | |
boolean getTempHumi(byte *temp, byte *humi) { | |
pinMode(DHT11_PIN, OUTPUT); | |
digitalWrite(DHT11_PIN, LOW); // Wake IC | |
delay(18); // Wait wake | |
pinMode(DHT11_PIN, INPUT_PULLUP); | |
delayMicroseconds(30); // pullup 20~40us | |
digitalRead(DHT11_PIN); | |
delayMicroseconds(50); // low 80us | |
while(!digitalRead(DHT11_PIN)); | |
delayMicroseconds(50); // high 80us | |
while(digitalRead(DHT11_PIN)); | |
byte b[4]; | |
byte sum = 0; | |
for (int i=0; i<4; i++) { | |
b[i] = _getbyte(); | |
sum += b[i]; | |
} | |
*humi = b[0]; | |
*temp = b[2]; | |
return sum == _getbyte(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment