#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#include <Wire.h>
// Initialize LCD object with address 0x3F, 16 columns, and 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variables for ultrasonic sensor, water level, set value, and pump state
long duration, inches;
int set_val, percentage;
bool state, pump;
void setup() {
// Begin serial communication at 9600 bps
Serial.begin(9600);
// Initialize and turn on the LCD
lcd.init();
lcd.backlight();
// Display initial messages on the LCD
lcd.print("WATER LEVEL:");
lcd.setCursor(0, 1);
lcd.print("PUMP:OFF MANUAL");
// Set pin modes for sensors and actuators
pinMode(2, OUTPUT); // Trigger pin for ultrasonic sensor
pinMode(3, INPUT); // Echo pin for ultrasonic sensor
pinMode(10, INPUT_PULLUP); // Button for setting water level manually
pinMode(11, INPUT_PULLUP); // Button for manual control of the pump
pinMode(6, OUTPUT); // Piezo buzzer control
pinMode(12, OUTPUT); // Pump control
pinMode(7, OUTPUT); // LED indicator for pump status
// Initialize the set value for water level
set_val = 25;
}
void loop() {
// Trigger ultrasonic sensor to measure distance
digitalWrite(2, HIGH);
delayMicroseconds(10);
digitalWrite(2, LOW);
duration = pulseIn(3, HIGH);
inches = microsecondsToInches(duration);
// Calculate the water level percentage
percentage = (set_val - inches) * 110 / set_val;
// Display water level percentage on the LCD
lcd.setCursor(12, 0);
if (percentage < 0)
percentage = 0;
lcd.print(percentage);
lcd.print("% ");
// Check water level and manual control button for pump activation
if (percentage < 30 && digitalRead(11)) {
pump = 1;
digitalWrite(7, HIGH); // Turn on pump indicator LED
}
// Check water level for pump deactivation
if (percentage > 85) {
pump = 0;
digitalWrite(7, LOW); // Turn off pump indicator LED
}
// Activate buzzer for low water level and manual mode
if (percentage < 30 && digitalRead(11)) {
tone(6, 262, 1000);
delay(3000);
}
// Display pump status on the LCD
lcd.setCursor(5, 1);
if (pump == 1)
lcd.print("ON ");
else if (pump == 0)
lcd.print("OFF");
// Display manual or auto mode on the LCD
lcd.setCursor(9, 1);
if (!digitalRead(11))
lcd.print("MANUAL ");
lcd.print("AUTO ");
// Check button states for setting water level manually or toggling pump state
if (!digitalRead(10) && !state && digitalRead(11)) {
state = 1;
set_val = inches;
EEPROM.write(0, set_val);
}
if (!digitalRead(10) && !state && !digitalRead(11)) {
state = 1;
pump = !pump;
}
if (digitalRead(10))
state = 0;
// Delay for stability and update the pump control
delay(500);
if (pump == 1 || percentage < 30) {
digitalWrite(12, HIGH); // Turn on the pump
} else {
digitalWrite(12, LOW); // Turn off the pump
}
// Print the state to Serial for debugging
Serial.println(state);
}
// Function to convert microseconds to inches
long microsecondsToInches(long microseconds) {
return microseconds / 29 / 2;
}