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

Posted 且听风吟-wuchao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Arduino下读取DHT22温湿度(不使用第三方库)相关的知识,希望对你有一定的参考价值。

代码如下:

#include <inttypes.h>
/*
 * LED
 */
 unsigned int LED = 13;
/*
 * DHT22配置程序
 */
unsigned int DHT_PIN = 7;

#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[5] = {0,0,0,0,0};
  unsigned char cnt = 7;
  unsigned char idx = 0;
  unsigned char sum;


  // REQUEST SAMPLE
  pinMode(DHT_PIN, OUTPUT);
  digitalWrite(DHT_PIN, LOW);
  delay(18);
  digitalWrite(DHT_PIN, HIGH);
  delayMicroseconds(40);
  pinMode(DHT_PIN, INPUT);

  // ACKNOWLEDGE or TIMEOUT
  unsigned int count = 10000;
  while(digitalRead(DHT_PIN) == LOW)
    if (count-- == 0) return DHT_ERR_TIMEOUT;

  count = 10000;
  while(digitalRead(DHT_PIN) == HIGH)
    if (count-- == 0) return DHT_ERR_TIMEOUT;

  // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
  for (int i=0; i<40; i++)
  {
    count = 10000;
    while(digitalRead(DHT_PIN) == LOW)
      if (count-- == 0) return DHT_ERR_TIMEOUT;

    unsigned long t = micros();

    count = 10000;
    while(digitalRead(DHT_PIN) == HIGH)
      if (count-- == 0) return DHT_ERR_TIMEOUT;

    if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
    if (cnt == 0)   // next byte?
    {
      cnt = 7;    // restart at MSB
      idx++;      // next byte!
    }
    else cnt--;
  }

  sum = bits[0]+bits[1]+bits[2]+bits[3];
  if(bits[4] != sum) return DHT_ERR_CHECK;
    

  humidity = (float)((bits[0] << 8)+bits[1])/10;
  temperature = (float)((bits[2] << 8)+bits[3])/10;
  
  return DHT_OK;
}

void setup() {
   pinMode(13,OUTPUT);//指示灯
   pinMode(DHT_PIN,INPUT);
   digitalWrite(DHT_PIN, HIGH);
}
void loop() {
   DHT_read();
   Serial.print("temperature:");
   Serial.println(temperature);
   Serial.println("============end===============");
   delay(1000);
   digitalWrite(LED,HIGH);
   delay(925); //Delay
   digitalWrite(LED,LOW);
   delay(925); //Delay
}

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

以上是关于Arduino下读取DHT22温湿度(不使用第三方库)的主要内容,如果未能解决你的问题,请参考以下文章

Arduino读取温湿度dh11+烟雾气体MQ2+彩灯ws2812

温湿度传感器DHT11

进阶之路(基础篇) - 012 Arduino IDE 添加DHT11传感器第三方库的方法

LabVIEW控制Arduino采集DHT11温湿度数值(进阶篇—4)

LabVIEW控制Arduino采集DHT11温湿度数值(进阶篇—4)

LabVIEW控制Arduino采集DHT11温湿度数值(进阶篇—4)