zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    处理在finally中出现的异常(Java)
    【转】alt和title属性的区别及应用
    IE6下兼容CSS属性minheight的解决办法
    javascript中判断字符串是否以指定字符串开始或结尾
    IE6兼容改造中的反思
    字符操作函数
    魔术公式
    抽象类和纯虚函数
    悬空指针
    重载
  • 原文地址:https://www.cnblogs.com/wuchaodzxx/p/8472635.html
Copyright © 2011-2022 走看看