#include <DHT.h>
#include <Servo.h> // servo library
const byte DHTpin = 3;
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTpin, DHTTYPE);
const byte servoTempPin = 4;
const byte servoHumiPin = 2;
Servo servoTemp;
Servo servoHumi;
float h, c, f, hOld, cOld = 0, fOld, hif, hifOld, hic, hicOld;
unsigned long timer, timeout = 2000; // delay between DHT reading
void setup() {
Serial.begin(115200);
Serial.println("Updates only occur when DHT changes.");
dht.begin();
servoTemp.attach(servoTempPin);
servoHumi.attach(servoHumiPin);
servoTemp.write(90); // start at servo "home"
servoHumi.write(90);
}
void loop() {
if (millis() - timer > timeout) { // delay between DHT reading
timer = millis();
h = dht.readHumidity();
c = dht.readTemperature();
f = dht.readTemperature(true);
// Uncomment for error checking
// if (isnan(h) || isnan(c) || isnan(f)) {
// Serial.println(F("Failed to read DHT."));
// return;
// }
}
hif = dht.computeHeatIndex(f, h);
hic = dht.computeHeatIndex(c, h, false);
if (h != hOld || c != cOld || f != fOld || hif != hifOld || hic != hicOld) {
hOld = h; cOld = c; fOld = f; hifOld = hif; hicOld = hic;
Serial.print(F("(Humidity:"));
pad(h);
Serial.print(h);
Serial.print(F("%) (Temperature:"));
pad(c);
Serial.print(c);
Serial.print(F("°C "));
pad(f);
Serial.print(f);
Serial.print(F("°F) (Heat index:"));
pad(hic);
Serial.print(hic);
Serial.print(F("°C "));
pad(hif);
Serial.print(hif);
Serial.println(F("°F)"));
}
int hMap = map(h, 0, 100, 0, 180);
int cMap = map(c, -40, 80, 0, 180);
servoHumi.write(hMap);
servoTemp.write(cMap);
}
void pad(float value) {
if (value <= -10.0) Serial.print(" ");
if (value > -10.0 && value < 0.0) Serial.print(" ");
if (value >= 0.0 && value < 10.0) Serial.print(" ");
if (value >= 10.0 && value < 100.0) Serial.print(" ");
if (value >= 100.0 && value < 1000.0) Serial.print(" ");
}
-40C
80C
60C
20C
40C
0C
-20C
0%
100%
80%
50%
65%
35%
20%