stm32在Arduino IDE开发环境下DHT22库导致死机

我是喜欢在Arduino IDE中开发stm32,因为觉得比较简单和省事(其实是自己菜)。今天在使用DHT库读取DHT22数据的时候突然卡死,单片机的绿灯一直闪烁,红灯常量,找了好久也不知道哪的问题,一点一点往下注释,最后发现是DHT库的问题了,但不知道具体是什么导致冲突了,然后就自己手动写一个DHT22的库吧,核心的代码是网上扒的,我给封进一个类里了,代码如下

DHT22.cpp

#include "DHT22.h"

DHT22::DHT22( unsigned int  pin ){
    
    
  DHT_PIN = pin;
}

float DHT22::readHumidity(){
    
    
  return humidity;
}

float DHT22::readTemperature(){
    
    
  return temperature;
}

void DHT22::begin(){
    
    
  pinMode(DHT_PIN,INPUT);
  digitalWrite(DHT_PIN, HIGH);
}

unsigned char DHT22::DHT22_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;
}

DHT22.h

#include "Arduino.h"
#include <inttypes.h>
#define DHT_OK      1
#define DHT_ERR_CHECK 0
#define DHT_ERR_TIMEOUT -1

class DHT22{
    
    
public:
  DHT22(unsigned int);
  float readTemperature();
  float readHumidity();
  void begin();
  unsigned char DHT22_read();
  
private:
  unsigned int DHT_PIN;
  float humidity;
  float temperature;
  
};

调用例子:

#include "mqtt.h"

// 传感器引脚
#define DHTPIN PB9

// 实例化
DHT22 dht22(DHTPIN);

void setup() {
    
    
  dht22.begin();
}

void loop() {
    
    
  // 采集数据
  dht22.DHT22_read();
  float T =  dht22.readTemperature();
  float H =  dht22.readHumidity();
}

猜你喜欢

转载自blog.csdn.net/u014117943/article/details/105980088
今日推荐