I am an absolute beginner to Arduino, but I am currently working on an IoT project. The goal is to see if temperature and humidity are changing drasticaly over a few minutes.
I am working with an ESP 8266, a DHT11 and the BLYNK App.
I have the following code, where I delay the time between two temperature reads, to calculate the difference between them. I know that delay() is not a good way to work, so I tried to rewrite it with a millis() timer. But it is not working! tempA just stays the same as tempB.
Can someone tell me, what it should look like correctly?
unsigned long previousMillis = 0;
const long interval = 5000;
void tempChange()
{
float tempA;
float tempB;
float tempDiff;
unsigned long currentMillis = millis();
tempA = dht.readTemperature();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
tempB = dht.readTemperature();
}
Serial.print(tempA);
Serial.print(" ");
Serial.println(tempB);
}
void setup()
{
dht.begin();
timer.setInterval(5000L, tempChange);
}
void loop()
{
Blynk.run();
timer.run();
}
If you know any better way, to record a change over time I am open to it. This was just the best (or worst) idea I have come up with.
Thank you!
The problem is that you are reading the same value twice. First you read it and assign it to
tempA
and then you do the same totempB
.tempA
is equal totempB
because it's the same reading!What you want to do is keep track of the previous temperature in a global variable and then, each time you call
tempChange()
, read the value of the sensor and get the difference. Then, change the value of the last temperature to the actual one for the next call.Also, you don't need to check the interval with
millis()
when calling the function because you are already calling it every "interval" milliseconds.