#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <ESP32Servo.h>
// Define pin connections
#define DHTPIN 23
#define DHTTYPE DHT11
#define TRIG_PIN 33
#define ECHO_PIN 32
#define LED_PIN 27
#define BUZZER_PIN 12
#define SERVO_PIN 13
#define SLIDE_SWITCH_PIN 5
// Initialize objects and variables
DHT dht(DHTPIN, DHTTYPE);
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Configure pin modes
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(SLIDE_SWITCH_PIN, INPUT_PULLUP);
// Attach servo
myservo.attach(SERVO_PIN);
// Initialize LCD and DHT sensor
lcd.init();
lcd.backlight();
dht.begin();
// Begin serial communication
Serial.begin(115200);
}
void loop() {
// Check the state of the slide switch
if (digitalRead(SLIDE_SWITCH_PIN) == HIGH) {
emergency();
} else {
runSensors();
}
delay(100); // Delay for 1 second
}
void runSensors() {
// Read temperature and humidity
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Measure distance using the ultrasonic sensor
long duration;
float distance;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2.0) * 0.0343; // Convert duration to meters
// Update LCD display
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature, 1);
lcd.print("C H:");
lcd.print(humidity);
lcd.print("%");
Serial.println(temperature);
lcd.setCursor(0, 1);
lcd.print("Water: ");
lcd.print(distance);
lcd.print("cm");
// Check water level and activate outputs
if (distance > 7) { // Water level threshold
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
delay(100);
digitalWrite(BUZZER_PIN, LOW);
delay(100); // Use tone function for ESP32
myservo.write(0); // Move servo to 0 degrees
} else {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW); // Stop buzzer
myservo.write(90); // Reset servo to 90 degrees
}
delay(500);
}
void emergency() {
// Activate all emergency outputs
digitalWrite(LED_PIN, HIGH);
myservo.write(0);
// Display emergency message
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Emergency!");
// Wait until the switch is toggled
while (digitalRead(SLIDE_SWITCH_PIN) == HIGH) {
digitalWrite(BUZZER_PIN, HIGH);
delay(100);
digitalWrite(BUZZER_PIN, LOW);
delay(100);
}
// Clear emergency state
lcd.clear();
myservo.attach(SERVO_PIN); // Reattach servo
}