#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <Servo.h>
#define DHTPIN 2
#define DHTTYPE DHT22
#define TRIG_PIN 3
#define ECHO_PIN 4
#define LED_PIN 7
#define BUZZER_PIN 8
#define SERVO_PIN 9
#define SLIDE_SWITCH_PIN 10
DHT dht(DHTPIN, DHTTYPE);
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(SLIDE_SWITCH_PIN, INPUT_PULLUP);
myservo.attach(SERVO_PIN);
lcd.init();
lcd.backlight();
dht.begin();
Serial.begin(9600);
}
void loop() {
// Check the state of the slide switch
if (digitalRead(SLIDE_SWITCH_PIN) == HIGH) {
emergency();
} else {
runSensors();
}
delay(1000); // Delay for 1 second
}
void runSensors() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
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.000343; // Convert to meters
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("C H:");
lcd.print(humidity);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Water: ");
lcd.print(distance);
lcd.print("m");
if (distance > 3.0) { // Check if water level is greater than threshold (3m)
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
tone(BUZZER_PIN, 100);
myservo.write(0); // Rotate servo to 0 degrees
} else {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
noTone(BUZZER_PIN);
myservo.write(90); // Rotate servo back to 90 degrees
}
}
void emergency() {
// Turn ON all outputs
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, 100);
myservo.write(0);
// Display emergency message
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Emergency!");
// Stay here until the switch is turned back on
while (digitalRead(SLIDE_SWITCH_PIN) == HIGH) {
delay(100);
}
// Clear emergency message and reattach servo
lcd.clear();
myservo.attach(SERVO_PIN);
}