// https://github.com/adafruit/DHT-sensor-library https://github.com/adafruit/Adafruit_Sensor
// NTC module = 1k ntc thermistor in series w/ 10k resistor.
#include "DHT.h"
#define USE_NTC_SENSOR
/*
Trigger the relay if the temperature reaches either
< TEMP_MIN or
> TEMP_MAX
*/
#define TEMP_MIN 0
#define TEMP_MAX 60
/// Pin configuration
#define DHT_PIN (2)
#define NTC_PIN (0)
#define RELAY_PIN (4)
//
namespace App
{
DHT* dhtSensor{nullptr};
float lastTemp{0.0f};
void Setup()
{
pinMode(RELAY_PIN, OUTPUT);
#ifndef USE_NTC_SENSOR
dhtSensor = new DHT(DHT_PIN, DHT22);
dhtSensor->begin();
#endif
}
/**
* Reads the current temeperature from a NTC or DHT sensor.
*
* @param float& current temperature
* @return bool operation successful?
*/
bool ReadTemperature(float* out)
{
if(dhtSensor != nullptr)
{
*out = dhtSensor->readTemperature();
}
else
{
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
*out = (1 / (log(1 / (1023. / analogRead(NTC_PIN) - 1)) / BETA + 1.0 / 298.15) - 273.15);
}
return !isnan(*out);
}
/**
* Toggles the relay.
*
* @param bool state true(open)/false(closed)
* @return void
*/
void ToggleRelay(bool state)
{
digitalWrite(RELAY_PIN, state?HIGH:LOW);
}
bool GetRelayState()
{
return (digitalRead(RELAY_PIN)==HIGH)?true:false;
}
void Loop()
{
delay(200);
static float temp{0.0f};
if(!ReadTemperature(&temp))
Serial.println("Failed to read temperature!"); // handle multiplie failed reads?
Serial.print(F("Temperature: "));
Serial.println(temp);
if(temp < TEMP_MIN || temp > TEMP_MAX)
ToggleRelay(true);
else if (GetRelayState())
ToggleRelay(false);
}
}
void setup() {
Serial.begin(9600);
App::Setup();
}
void loop() {
App::Loop();
}