#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <NewPing.h>
// Define the pins for the ultrasonic sensor
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define BuzzerPin 12
float hight;
float redious=365.764;
// Define the pin for the pump
#define PUMP_PIN 7
// Define the water level threshold points
#define LOW_THRESHOLD 20 // Water level below this threshold, turn on the pump
#define HIGH_THRESHOLD 90 // Water level above this threshold, turn off the pump
#define DANGER_THRESHOLD 95 // Water level above this threshold, turn off the pump
// Create an instance of the NewPing library
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Set the pump pin as an output
pinMode(PUMP_PIN, OUTPUT);
pinMode(BuzzerPin, OUTPUT);
// Initialize serial communication
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight();
// Print initial messages on the LCD
lcd.setCursor(0, 0);
lcd.print("Water Level:");
lcd.setCursor(0, 1);
lcd.print("Pump Status:");
}
void loop() {
// Measure distance using ultrasonic sensor
int distance = sonar.ping_cm();
// Check if there's an error in distance measurement
if (distance == 0) {
Serial.println("Error: Distance measurement failed!");
return;
}
// Print the distance measured on the serial monitor
float hight = 400-distance;
int waterquantity = map(distance, 0, 400, 100, 0);
Serial.print("Water Level: ");
Serial.print(waterquantity);
Serial.println(" %");
// Display the distance on the LCD
lcd.setCursor(12, 0);
lcd.print(" "); // Clear previous value
lcd.setCursor(12, 0);
lcd.print(waterquantity );
lcd.print("%");
measured_volume(hight,redious);
// Check if the water level is below the low threshold
if ((waterquantity <= LOW_THRESHOLD))
{
// Water level is low, turn on the pump
digitalWrite(PUMP_PIN, HIGH);
digitalWrite(BuzzerPin, LOW);
Serial.println("Water level low! Pump turned on.");
// Update pump status on the LCD
lcd.setCursor(12, 1);
lcd.print("ON ");
}
// Check if the water level is above the high threshold
else if ((waterquantity >= HIGH_THRESHOLD) )
{
// Water level is high, turn off the pump
digitalWrite(PUMP_PIN, LOW);
digitalWrite(BuzzerPin, LOW);
Serial.println("Water level high! Pump turned off.");
// Update pump status on the LCD
lcd.setCursor(12, 1);
lcd.print("OFF");
}
if ((waterquantity >= DANGER_THRESHOLD) )
{
// Water level is high, turn off the pump
digitalWrite(BuzzerPin, HIGH);
//Serial.println("Water level high! Pump turned off.")
// Update pump status on the LCD
lcd.setCursor(12, 1);
lcd.print("@*@");
}
// Delay before next measurement
delay(1000); // Adjust delay time as needed
}
void mesured_volume(float h, float r )
{
float volume = (3.14*(r^2)*h);
Serial.print(volume);
}