I've got a bit of a puzzler.
This is my first big project with an Arduino (Mega 2560,) and I've run into something odd. In the code pasted in below, things work perfectly as-is. However, if I comment out the readSensors() call inside the loop and uncomment it from inside the timer, the first sensor will always fail to read. I've tried different inputs, flopping the inputs, adding in a delay, and no matter what I've tried, whatever input is first will fail to read every time when I call the function from inside the timer. I also tried placing the read code directly inside the timer, and experienced the same results.
Any thoughts?
#include "DHT.h"
#define DHTPIN 9 // left sensor
#define DHTPIN2 8 //right sensor
#define gled 10 //green LED
#define rled 11 //red LED
int timer1_counter;
int timer_cycle;
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
void setup()
{
Serial.begin(9600);
dht.begin();
dht2.begin();
pinMode(gled, OUTPUT);
pinMode(rled, OUTPUT);
// initialize timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
// Set timer1_counter to the correct value for our interrupt interval
timer1_counter = 3036; // ends up with 1 second intervals
TCNT1 = timer1_counter; // preload timer
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER1_OVF_vect) // interrupt service routine
{
TCNT1 = timer1_counter; // preload timer
timer_cycle++;
digitalWrite(gled, digitalRead(gled) ^ 1); //blink green LED
if (timer_cycle >= 10) { //execute every 10s
timer_cycle = 0;
digitalWrite(rled, digitalRead(rled) ^ 1); //toggle red LED
//readSensors();
}
}
void loop()
{
readSensors();
delay(5000);
}
void readSensors() {
// 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();
float t = dht.readTemperature();
h = dht.readHumidity();
t = dht.readTemperature();
float h2 = dht2.readHumidity();
float t2 = dht2.readTemperature();
if (isnan(t)) { t = 0; }
if (isnan(t2)) { t2 = 0; }
if (isnan(h)) { h = 0; }
if (isnan(h2)) { h2 = 0; }
Serial.print("Humidity 1: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature 1: ");
Serial.print(t * 1.8 + 32);
Serial.println(" *F");
Serial.print("Humidity 2: ");
Serial.print(h2);
Serial.print(" %\t");
Serial.print("Temperature 2: ");
Serial.print(t2 * 1.8 + 32);
Serial.println(" *F");
Serial.println("");
}