DHT22 Fails read after Serial.println

I noticed, when using a DHT22, the read must be done at least 5ms after any Serial.println.

The example "SimpleDHT - DHT22Default" will show this: the read sometimes fails multiple times.

Adding a delay after the serial before read2, will fix.

Serial.println("Sample DHT22...");
delay(5); // add this

You can have a better visualization of the error using the example "DHT22ErrCount": it works 100% as it is, but if you add a Serial.println(); before the read2, you'll see the success rate dropping to very low levels.

```
Serial.println("=================================");
if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
  Serial.print("Read DHT22 failed, err="); Serial.println(err);err_cnt++;
}
```

This way I got 66% error rate instead of 100%.

So, before any usage of the read2 function, add a delay(5) and you'll be safe.
I haven't checked other conditions, it may apply also to other functions or sensor (probably DHT11) .

Post code.

Here the full code, modified by adding this row:

    Serial.println("== READ2 MAY FAIL AFTER THIS ==");  // PRINT SERIAL BEFORE READ2
#include <SimpleDHT.h>

// for DHT22, 
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT22 = 2;
SimpleDHT22 dht22;

void setup() {
  Serial.begin(115200);
}

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT22 with error count");

  int cnt = 0;
  int err_cnt = 0;
  for (;;) {
    cnt++;

    float temperature = 0;
    float humidity = 0;
    int err = SimpleDHTErrSuccess;
   
    Serial.println("== READ2 MAY FAIL AFTER THIS ==");  // PRINT SERIAL BEFORE READ2

    if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
      Serial.print("Read DHT22 failed, err="); Serial.println(err);err_cnt++;
    }

    Serial.print((float)temperature); Serial.print(" *C, ");
    Serial.print((float)humidity); Serial.print(" RH%");
    Serial.print(", total: "); Serial.print(cnt);
    Serial.print(", err: "); Serial.print(err_cnt);
    Serial.print(", success rate: "); Serial.print((cnt - err_cnt) * 100.0 / (float)cnt); Serial.println("%");

    delay(2500);
  }
}

This way the example DHT22ErrCount will produce an error rate < 100%.

What if you try

This solves the problem too.

So do you think it happens because the serial is still transmitting, and by flushing we make sure the transmission is completed?

I also noticed, when using pin 2 or 4 it works as we've seen until now (it works unless you print without flushing/delay), with pin 3 or 5, instead, it fails a lot , even without print or with print +flush.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.