Arduino下读取DHT22温湿度(不使用第三方库)

代码如下:

#include <inttypes.h>
/*
* LED
*/
unsigned int LED = ;
/*
* DHT22配置程序
*/
unsigned int DHT_PIN = ; #define DHT_OK 1
#define DHT_ERR_CHECK 0
#define DHT_ERR_TIMEOUT -1
float humidity;
float temperature;
unsigned char DHT_read()
{
// BUFFER TO RECEIVE
unsigned char bits[] = {,,,,};
unsigned char cnt = ;
unsigned char idx = ;
unsigned char sum; // REQUEST SAMPLE
pinMode(DHT_PIN, OUTPUT);
digitalWrite(DHT_PIN, LOW);
delay();
digitalWrite(DHT_PIN, HIGH);
delayMicroseconds();
pinMode(DHT_PIN, INPUT); // ACKNOWLEDGE or TIMEOUT
unsigned int count = ;
while(digitalRead(DHT_PIN) == LOW)
if (count-- == ) return DHT_ERR_TIMEOUT; count = ;
while(digitalRead(DHT_PIN) == HIGH)
if (count-- == ) return DHT_ERR_TIMEOUT; // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
for (int i=; i<; i++)
{
count = ;
while(digitalRead(DHT_PIN) == LOW)
if (count-- == ) return DHT_ERR_TIMEOUT; unsigned long t = micros(); count = ;
while(digitalRead(DHT_PIN) == HIGH)
if (count-- == ) return DHT_ERR_TIMEOUT; if ((micros() - t) > ) bits[idx] |= ( << cnt);
if (cnt == ) // next byte?
{
cnt = ; // restart at MSB
idx++; // next byte!
}
else cnt--;
} sum = bits[]+bits[]+bits[]+bits[];
if(bits[] != sum) return DHT_ERR_CHECK; humidity = (float)((bits[] << )+bits[])/;
temperature = (float)((bits[] << )+bits[])/; return DHT_OK;
} void setup() {
pinMode(,OUTPUT);//指示灯
pinMode(DHT_PIN,INPUT);
digitalWrite(DHT_PIN, HIGH);
}
void loop() {
DHT_read();
Serial.print("temperature:");
Serial.println(temperature);
Serial.println("============end===============");
delay();
digitalWrite(LED,HIGH);
delay(); //Delay
digitalWrite(LED,LOW);
delay(); //Delay
}

DHT22数据手册:http://www.waveshare.net/w/upload/b/be/AM2302_V1.1.pdf

上一篇:S5PV210 ADC转换


下一篇:活动精彩实录 | 王峰:Cassandra在360的多场景应用及未来趋势