#include "DHT.h"
#include "LiquidCrystal_I2C.h"
#include "RTClib.h"
#define DHTPIN 27
RTC_DS1307 rtc;
#define DHTTYPE DHT22
int relay = 13, r = 32;
int reNF;
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
pinMode(relay, OUTPUT);
lcd.init();
lcd.backlight();
dht.begin();
#ifndef ESP8266
while (!Serial);
#endif
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (1) delay(10);
}
}
void loop() {
DateTime now = rtc.now();
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
int val = analogRead(r);
float v = val * 3.3 / 4095;
int PR = map(val, 0, 4095, 0, 100);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%, Potentiometer Voltage: ");
Serial.print(v);
Serial.print("V, Time: ");
Serial.print(now.hour());
Serial.print(":");
Serial.print(now.minute());
Serial.print(":");
Serial.print(now.second());
Serial.print(", Relay: ");
// Control relay based on humidity and potentiometer voltage
if (h > 65 && v < 1.7) {
// Calculate the time elapsed since the last 18-second interval
int timeElapsed = now.second() % 18;
//The relay will turn on every 18 seconds (18, 36, 54, etc.).
//It will stay on for 3 seconds before turning off (18 + 3 = 21, 36 + 3 = 39, 54 + 3 = 57, etc.).
// Turn on the relay if it's within the first 3 seconds of the 18-second interval
if (timeElapsed < 3) {
digitalWrite(relay, HIGH);
reNF = 1;
Serial.print("ON");
} else {
// Otherwise, turn off the relay
digitalWrite(relay, LOW);
reNF = 0;
Serial.print("OFF");
}
} else if (h < 65 && v > 1.7) {
// If conditions are not met, turn off the relay
digitalWrite(relay, LOW);
reNF = 0;
Serial.print("OFF");
}
Serial.println();
// Display humidity and potentiometer voltage on LCD line 1
lcd.setCursor(0, 0);
lcd.print("H:");
lcd.print(h);
lcd.print("% P:");
lcd.print(v);
lcd.print("V");
// Display time and relay status on LCD line 2
lcd.setCursor(0, 1);
lcd.print("T:");
lcd.print(now.hour());
lcd.print(":");
lcd.print(now.minute());
lcd.print(":");
lcd.print(now.second());
lcd.print("R: ");
if (reNF == 1) {
lcd.print("ON");
} else {
lcd.print("OFF");
}
if (now.second() == 59) {
delay(500);
lcd.clear();
}
delay(500);
}