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