Erroneous data from DHT11 when using TimerOne.h

I’m working on a project with an UNO, DHT11, 1602 display, MH-SD card module, and a few other odds and ends. The system will gather info from sensors and either trigger some output or write to the card (high/low temps, etc). Most of the interactions are pretty straightforward and work without issue.

My problem on this project is using timer interrupts to pull data from DHT11 at regular intervals. I’ve tried using TimerOne, but the data back from the DHT11 is bogus (-999 or 0 usually). Is there something I need to do differently? Here’s a short example using just TimerOne and the DHT. Behavior is the same whether you print from loop() or the ISR. It does display correctly if you comment out the Timer1 functions and call readdht11() from loop.

#include <TimerOne.h>
#include <dht.h>
dht DHT;

void setup() {
  Serial.begin(9600);
  Timer1.initialize(2000000);
  Timer1.attachInterrupt(readdht11);
}

void loop() {
}

void readdht11() {
  int readData = DHT.read11(6);
  float t = DHT.temperature;
  float h = DHT.humidity;
  Serial.println(t);
}

Any help would be appreciated!

My problem on this project is using timer interrupts to pull data from DHT11 at regular intervals.

Don't use interrupts for this. Many things on the Arduino platform depend on interrupts to work (using Serial is one of these). As interrupts are disabled in interrupt context, you must not use these things in an interrupt handler (as you do in readdht11() ).

Use millis() to call actions on a regularly basis, the example sketch BlinkWithoutDelay shows you how to use it.

The DHT sensors use a serial stream of bits in both directions. That takes time. Most libraries for DHT turn of interrupts to do the precise timing. That means you can not use it in a interrupt, use the DHT functions in the loop().

Since you are moving the DHT functions to the loop(), you should use millis() to that every 2 seconds. The famous Blink Without Delay example is mentioned so often, some abbriviate it to "BWD" : https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

Since you are going to use millis(), you can add other millis() timers to update the display, to blink a led, to write to the SD card. All at different intervals and everything together.

Much thanks to both of you! I wondered if the best answer wouldn't be a simpler solution. Millis looks like it will do the trick.

It sure will, and it is fun as well :smiley: