#include <DHT.h>
#include <ESP32Servo.h>
#include <LiquidCrystal.h>
#define DHTPIN 15
#define DHTTYPE DHT22
#define LDR_PIN 34
#define RELAY_PIN 32
#define SERVO_PIN 5
#define TRIG_PIN 12
#define ECHO_PIN 14
#define RED_PIN 25
#define GREEN_PIN 26
#define BLUE_PIN 27
// Define LCD pins
const int RS_PIN = 21;
const int EN_PIN = 13;
const int D4_PIN = 19;
const int D5_PIN = 18;
const int D6_PIN = 16;
const int D7_PIN = 17;
LiquidCrystal lcd(RS_PIN, EN_PIN, D4_PIN, D5_PIN, D6_PIN, D7_PIN);
DHT dht(DHTPIN, DHTTYPE);
Servo myservo;
void setup() {
Serial.begin(9600);
dht.begin();
pinMode(LDR_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
myservo.attach(SERVO_PIN);
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
/*
// Initialize LED channels
ledcSetup(0, 5000, 8);
ledcSetup(1, 5000, 8);
ledcSetup(2, 5000, 8);
ledcAttachPin(RED_PIN, 0);
ledcAttachPin(GREEN_PIN, 1);
ledcAttachPin(BLUE_PIN, 2);
*/
}
void loop() {
// Reading sensors
float h = dht.readHumidity();
float t = dht.readTemperature();
int ldrValue = analogRead(LDR_PIN);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Ultrasonic sensor distance measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
int distance = duration * 0.034 / 2;
// Display on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: "); lcd.print(t); lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Hum: "); lcd.print(h); lcd.print(" %");
delay(2000); // Display for 2 seconds
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Light: "); lcd.print(ldrValue);
lcd.setCursor(0, 1);
lcd.print("Dist: "); lcd.print(distance); lcd.print(" cm");
delay(2000); // Display for 2 seconds
// Control RGB Bulb
if (ldrValue < 500) { // adjust threshold
digitalWrite(RED_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
////ledcWrite(0, 255); // Red light for low light
//ledcWrite(1, 0);
//ledcWrite(2, 0);
} else {
digitalWrite(RED_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
}
// Watering plant using relay if distance < certain threshold
if (distance < 10) {
digitalWrite(RELAY_PIN, HIGH);
delay(2000);
digitalWrite(RELAY_PIN, LOW);
}
// Move servo based on temperature
if (t > 30) {
myservo.write(90); // Open position
} else {
myservo.write(0); // Closed position
}
delay(5000); // Delay between readings
}