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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值