#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const int trigPin = 2;
const int echoPin = 3;
const int buzzerPin = 4;
const float tankCapacityLiters = 6.0; // Maximum capacity of the water tank in liters
const float tankCapacityCM = 6000.0; // Maximum capacity of the water tank in cubic centimeters
const float minDistanceCM = 2.0; // Minimum distance from the sensor to the water level in centimeters
const float tankDiameterCM = 10.0; // Diameter of the tank in centimeters
void setup() {
lcd.begin(16, 2); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
long duration;
float distance, waterLevelPercentage;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read ultrasonic echo
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Convert distance to water level percentage
waterLevelPercentage = ((tankCapacityCM - distance * tankDiameterCM * tankDiameterCM * 0.25) / tankCapacityCM) * 100.0;
waterLevelPercentage = constrain(waterLevelPercentage, 0, 100); // Ensure percentage is within 0-100 range
// Print distance and water level percentage on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Water Level Percentage: ");
Serial.print(waterLevelPercentage);
Serial.println("%");
// Print water level percentage on LCD
lcd.clear(); // Clear previous content
lcd.setCursor(0, 0); // Set cursor to first column, first row
lcd.print("Water Level:");
lcd.setCursor(0, 1); // Set cursor to first column, second row
lcd.print(waterLevelPercentage);
lcd.print("%");
// Check if water level is almost full (e.g., 90%)
if (waterLevelPercentage >= 90) {
// Activate buzzer for 2 seconds
digitalWrite(buzzerPin, HIGH);
delay(2000);
digitalWrite(buzzerPin, LOW);
}
delay(1000); // Delay for readability, adjust as needed
}