#include <LiquidCrystal.h>
// Define LCD pins
const int rs = 12;
const int en = 11;
const int d4 = 5;
const int d5 = 4;
const int d6 = 3;
const int d7 = 2;
// Define ultrasonic sensor pins
const int trigPin = 9;
const int echoPin = 10;
// Define LED pin
const int ledPin = 7;
// Define buzzer pin
const int buzzerPin = 6;
// Define slide switch pin
const int switchPin = A0;
// Maximum distance (in cm) the ultrasonic sensor can measure
const int maxDistance = 400;
// Threshold for triggering the buzzer (water level below which alarm triggers)
const int buzzerThreshold = 30;
// Initialize LCD
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set up LCD
lcd.begin(16, 2);
// Set up ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set up LED and buzzer pins
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Set up slide switch pin
pinMode(switchPin, INPUT);
}
void loop() {
// Variables to store the distance and water level
float distance;
int waterLevel;
// Trigger ultrasonic sensor to send pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the pulse travel time to calculate distance (in cm)
distance = pulseIn(echoPin, HIGH) / 58.0; // Divide by conversion factor
// Map distance to water level percentage
waterLevel = map(distance, 0, maxDistance, 0, 100);
// Ensure water level stays within 0-100 range
waterLevel = constrain(waterLevel, 0, 100);
// Print water level to serial monitor
Serial.print("Water Level: ");
Serial.print(waterLevel);
Serial.println("%");
// Display water level on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Water Level:");
lcd.setCursor(0, 1);
lcd.print(waterLevel);
lcd.print("%");
// Check if water level is below the buzzer threshold
if (waterLevel <= buzzerThreshold) {
// Activate LED and buzzer for alarm
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 1000); // Buzzer sound
// Open the switch
digitalWrite(switchPin, HIGH);
Serial.println("Switch is OPEN");
} else {
// Turn off LED and buzzer
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
// Close the switch
digitalWrite(switchPin, LOW);
Serial.println("Switch is CLOSED");
}
// Delay before next reading
delay(1000);
}