#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the LCD (address 0x27 for most 16x2 I2C LCDs)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Pin definitions
const int trigPin = 13;
const int echoPin = 12;
const int relayPin = 14;
// Water level threshold distances in cm
const int minDistance = 10; // Minimum distance to turn on pump (tank empty)
const int maxDistance = 300; // Maximum distance to turn off pump (tank full)
void setup() {
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
// Initialize relay to be off
digitalWrite(relayPin, LOW);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Tank Level:");
}
long getDistance() {
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the echo pulse width
long duration = pulseIn(echoPin, HIGH);
// Convert the pulse width to distance in cm
long distance = duration * 0.034 / 2;
return distance;
}
void loop() {
long distance = getDistance();
// Calculate tank level percentage
int tankLevel = map(distance, minDistance, maxDistance, 100, 0);
tankLevel = constrain(tankLevel, 0, 100); // Keep value between 0% and 100%
// Display tank level on LCD
lcd.setCursor(0, 1);
lcd.print("Level: ");
lcd.print(tankLevel);
lcd.print(" % ");
// Pump control logic
if (distance <= minDistance+1) {
// Tank is full; turn off pump
digitalWrite(relayPin, LOW);
} else if (distance >= 70) {
// Tank is empty; turn on pump
digitalWrite(relayPin, HIGH);
}
delay(1000); // Update every second
}