Reputation: 11
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!
Upvotes: 0
Views: 757
Reputation: 560
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 to tempB
. tempA
is equal to tempB
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.
//Create a global variable to keep track of the previous temperature
float previousTemp = dht.readTemperature();
//Call this every "interval" milliseconds
void tempChange()
{
//Get current temperature and calculate temperature difference
float currentTemp = dht.readTemperature();
float tempDiff = currentTemp-previousTemp;
//Keep track of previous temp
previousTemp = currentTemp
//Print results
Serial.println(previousTemp + " " + currentTemp);
Serial.println("Change: " + tempDiff);
}
Also, you don't need to check the interval with millis()
when calling the function because you are already calling it every "interval" milliseconds.
Upvotes: 2