CODE
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define trigPin 9
#define echoPin 10
#define relayPin 8
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3,POSITIVE);
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
lcd.begin(16, 2);
lcd.setBacklight(1); // Turn on the LCD backlight
lcd.setCursor(0, 0);
lcd.print("Water Tank");
digitalWrite(relayPin, LOW); // Ensure relay is off initially
}
void loop() {
long duration, distance;
// Trigger the ultrasonic sensor to send a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time for the pulse to return
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = (duration / 2) * 0.0344;
// Display the water level based on the distance
lcd.setCursor(0, 1);
if (distance <= 4) {
lcd.print("Full Water Tank");
digitalWrite(relayPin, HIGH); // Turn off relay
}
else if (distance <= 20) {
lcd.print("Half Water level");
}
else if (distance <= 30) {
lcd.print("Low Water Level");
digitalWrite(relayPin, LOW); // Turn on relay
}
else {
lcd.print("Low Water Level");
digitalWrite(relayPin, LOW); // Ensure relay is off
}
delay(100); // Delay for stability
}