retry once if temp reading fails

This commit is contained in:
Nicu Hodos 2021-12-30 20:26:42 +01:00
parent 0ce4ca5637
commit cdb0711ba6

View File

@ -4,8 +4,8 @@
#include <TinyPower.h> #include <TinyPower.h>
#include <DHT.h> #include <DHT.h>
#define SEND_INTERVAL (int)(5*60/8) #define SEND_INTERVAL 37 // 37*8s = ~5min
#define SEND_VCC_INTERVAL (int)(60*60/8) #define SEND_VCC_INTERVAL (SEND_INTERVAL*6) // every half hour
// Pins // Pins
#define TEMP_POSITIVE PIN_B3 #define TEMP_POSITIVE PIN_B3
@ -15,8 +15,11 @@
struct DhtValues { struct DhtValues {
int temperature; int temperature;
int humidity; int humidity;
bool success;
}; };
DhtValues readTemp(); DhtValues readTemp();
void turnOnDht();
void turnOffDht();
TempSensor tempSensor = TempSensor(TEMP_SENSOR); TempSensor tempSensor = TempSensor(TEMP_SENSOR);
HumiditySensor humidSensor = HumiditySensor(TEMP_SENSOR); HumiditySensor humidSensor = HumiditySensor(TEMP_SENSOR);
@ -37,34 +40,54 @@ void setup() {
} }
void loop() { void loop() {
if (counter % SEND_INTERVAL == 0) { static bool retry = false;
if (retry || (counter % SEND_INTERVAL == 0)) {
DhtValues values = readTemp(); DhtValues values = readTemp();
if (counter % SEND_VCC_INTERVAL == 0) { if (values.success) {
tempSensor.sendTempAndVoltage(values.temperature); if (counter % SEND_VCC_INTERVAL == 0) {
counter = 0; tempSensor.sendTempAndVoltage(values.temperature);
} else { counter = 0;
tempSensor.sendTemp(values.temperature); } else {
tempSensor.sendTemp(values.temperature);
}
delay(100);
humidSensor.sendHumidity(values.humidity);
turnOffDht();
} }
delay(100); if (retry && !values.success) {
humidSensor.sendHumidity(values.humidity); turnOffDht();
}
retry = !retry && !values.success;
} }
TinyPower::sleep(); TinyPower::sleep();
} }
DhtValues readTemp() { DhtValues readTemp() {
DhtValues dhtValues; DhtValues dhtValues;
dhtValues.temperature = roundf(dht.readTemperature() * 10); float temp = dht.readTemperature();
dhtValues.humidity = roundf(dht.readHumidity() * 10); float humid = dht.readHumidity();
digitalWrite(TEMP_POSITIVE, LOW); dhtValues.success = !isnan(temp) && !isnan(humid);
pinMode(DHT_PIN, OUTPUT); dhtValues.temperature = roundf(temp * 10);
digitalWrite(DHT_PIN, LOW); dhtValues.humidity = roundf(humid * 10);
return dhtValues; return dhtValues;
} }
ISR(WDT_vect) { ISR(WDT_vect) {
counter++; counter++;
if (((counter + 1) % SEND_INTERVAL == 0) || ((counter + 1) % SEND_VCC_INTERVAL == 0)) { if (((counter + 1) % SEND_INTERVAL == 0) || ((counter + 1) % SEND_VCC_INTERVAL == 0)) {
pinMode(DHT_PIN, INPUT_PULLUP); turnOnDht();
digitalWrite(TEMP_POSITIVE, HIGH);
} }
} }
void turnOnDht() {
pinMode(DHT_PIN, INPUT_PULLUP);
digitalWrite(TEMP_POSITIVE, HIGH);
}
void turnOffDht() {
digitalWrite(TEMP_POSITIVE, LOW);
pinMode(DHT_PIN, OUTPUT);
digitalWrite(DHT_PIN, LOW);
}