#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define trigPin 9 // Pin connected to the trigger input of the ultrasonic sensor
#define echoPin 10 // Pin connected to the echo output of the ultrasonic sensor
#define buzzerPin 7 // Pin connected to the positive input of the buzzer
#define relayPin 8 // Pin connected to the relay module
int waterLevelThreshold = 50; // Adjust this value according to your setup and desired water level
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(relayPin, OUTPUT);
}
void loop() {
long duration, distance;
// Trigger ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
distance = (duration / 2) * 0.0343;
// Display distance on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Water Level: ");
lcd.print(distance);
lcd.print(" cm");
// Check water level
if (distance < waterLevelThreshold) {
// Water level is below threshold, activate buzzer and relay
digitalWrite(buzzerPin, HIGH);
digitalWrite(relayPin, HIGH);
lcd.setCursor(0, 1);
lcd.print("Low! Buzzer On");
Serial.println("Water level is low! Buzzer and relay activated.");
} else {
// Water level is above threshold, deactivate buzzer and relay
digitalWrite(buzzerPin, LOW);
digitalWrite(relayPin, LOW);
lcd.setCursor(0, 1);
lcd.print(" ");
}
delay(1000); // Adjust the delay as needed
}