#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, 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) / 29.1;
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
if (distance > 100) { // Check if water level is high
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
myservo.write(0); // Rotate servo to 90 degrees
} else {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
myservo.write(90); // Rotate servo back to 0 degrees
}
}
void emergency() {
// Turn ON all outputs
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
myservo.write(0);
// Display emergency message
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Emegency!");
// 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);
}