Skip to content

Improvement: Not lock / hangs when DHT22 is still not ready. #176

@Anyeos

Description

@Anyeos
  • Arduino board: Bluepill STM32F103

  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.8.13

  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too):

If I try to read the sensor before the two seconds delay after powering up the board, the library locks the entire program.
It may be of use if the library simply ignores the reading and do not lock the program flow.
The unlocking behaviour can help in situations where the sensors can get disconnected or can lost power or data conection randomly (or in a hot plug manner).
The actual behaviour of get locked on the read call can sometimes difficult debuging more complex applications. That was my situation where my applitacion worked while developing / programming but not on production (because I just powered the board some seconds before uploading the sketch, giving enouth time for the DHT being ready. But on production the program starts inmediately and don't give enough time for DHT being ready).

Of course, I must actually use a delay of two seconds before reading something from the sensor and it works for now.

Code example:

#include "DHT.h"

DHT dht(PA3, DHT22);

void setup() {
  Serial.begin(115200);
  Serial.println(F("DHTxx test!"));

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  // Try without the delay and with the delay to test it
  // Don't forget to turn on the board and the sensor at the same time.
  //delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions