码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-02-26 15:10:44      阅读:1002      评论:0      收藏:0      [点我收藏+]

标签:turn   dht   arduino   inpu   使用   wave   idt   setup   define   

代码如下:

#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温湿度(不使用第三方库)

标签:turn   dht   arduino   inpu   使用   wave   idt   setup   define   

原文地址:https://www.cnblogs.com/wuchaodzxx/p/8472635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!