#include <DHT.h>
#include <LiquidCrystal_I2C.h>
//Pin definitions for the Thermostat components.
#define DHTPIN 2
#define DHTTYPE DHT22
#define RELAY_PIN 8
#define RED_PIN 9
#define GREEN_PIN 10
#define BLUE_PIN 11
#define INCREASE_BTN 3
#define DECREASE_BTN 4
//Libraries used for the thermostat project.
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
//These variable will be used to control the temperature and humidity levels in the thermostat.
float currentTemp = 25.0;
float targetTemp = 25.0;
float humidity = 50.0;
//Initializaing the Serial monitor, DHT Sensor and LCD.
void setup() {
Serial.begin(9600);
dht.begin();
lcd.init();
lcd.backlight();
//Set the LED pins as output and button pins as input.
pinMode(RELAY_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
pinMode(INCREASE_BTN, INPUT_PULLUP);
pinMode(DECREASE_BTN, INPUT_PULLUP);
// Start with green LED
setLEDColor(0, 255, 0);
}
void loop() {
readSensor();
checkButtons();
updateLCD();
controlRelay();
updateLED();
delay(100);
}
void readSensor() {
float newTemp = dht.readTemperature();
float newHumidity = dht.readHumidity();
if (!isnan(newTemp) && !isnan(newHumidity)) {
currentTemp = newTemp;
humidity = newHumidity;
}
}
//Controlling the temperature based on the buttons. Buttons upon being pressed, can alter the temperature.
void checkButtons() {
if (digitalRead(INCREASE_BTN) == LOW) {
targetTemp += 1;
delay(200); // Debounce
}
if (digitalRead(DECREASE_BTN) == LOW) {
targetTemp -= 1;
delay(200); // Debounce
}
}
//Display the temperature and humidity level readings on the LCD we've used.
void updateLCD() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(currentTemp, 1);
lcd.print("C ");
lcd.print(targetTemp, 1);
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity, 1);
lcd.print("%");
}
//Controlling the relay according to the temperature. If the set temp.> room temp. then the relay turns on the heating. If the set temp.< room temp. then the relay turns off the heating.
void controlRelay() {
if (currentTemp < targetTemp) {
digitalWrite(RELAY_PIN, HIGH); // Turn on heating
} else {
digitalWrite(RELAY_PIN, LOW); // Turn off heating
}
}
//Changing the color of the LED based on the temperature. If the set temp.> current temp. then led turns red. If set temp.< current temp. then led turns blue. If set temp.= current temp. then led turns green.
void updateLED() {
if (currentTemp < targetTemp) {
setLEDColor(0, 0, 255); // Blue
} else if (currentTemp > targetTemp) {
setLEDColor(255, 0, 0); // Red
} else {
setLEDColor(0, 255, 0); // Green
}
}
void setLEDColor(int red, int green, int blue) {
analogWrite(RED_PIN, red);
analogWrite(GREEN_PIN, green);
analogWrite(BLUE_PIN, blue);
}