#include <Wire.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>
// Create an LCD object with pins specified
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
long duration, inches; // Variables for distance and water level
int set_val, percentage; // Variables for set value and percentage
bool state, pump; // Flags for button state and pump control
void setup() {
// Initialize LCD and print initial messages
lcd.begin(16, 2);
lcd.print("WATER LEVEL:");
lcd.setCursor(0, 1);
lcd.print("PUMP:OFF MANUAL");
// Set pin modes for sensor, pump, and buttons
pinMode(8, OUTPUT); // Trigger pin for ultrasonic sensor
pinMode(9, INPUT); // Echo pin for ultrasonic sensor
pinMode(10, INPUT_PULLUP); // Button for setting value
pinMode(11, INPUT_PULLUP); // Button for automatic/manual mode
pinMode(12, OUTPUT); // Pump control pin
pinMode(13, OUTPUT); // Buzzer control pin
// Read set value from EEPROM (non-volatile memory)
set_val = EEPROM.read(0);
// Limit set value to a maximum of 150
if (set_val > 150) set_val = 150;
}
void loop() {
// Trigger the ultrasonic sensor and measure duration
digitalWrite(8, LOW);
delayMicroseconds(2);
digitalWrite(8, HIGH);
delayMicroseconds(10);
digitalWrite(8, LOW);
duration = pulseIn(9, HIGH);
// Convert duration to inches
inches = microsecondsToInches(duration);
// Calculate water level percentage
percentage = (set_val - inches) * 100 / set_val;
// Ensure percentage is not negative
if (percentage < 0) percentage = 0;
// Display water level percentage on LCD
lcd.setCursor(12, 0);
lcd.print(percentage);
lcd.print("% ");
// Control pump based on water level and mode
if (percentage < 30 && digitalRead(11)) { // If in auto mode and level low
pump = 1; // Turn on pump
} else if (percentage > 99) { // If level high
pump = 0; // Turn off pump
}
digitalWrite(12, !pump); // Invert signal for pump control
// Control buzzer based on water level
if (percentage <= 20) {
tone(13, 262, 250); // Play a tone on the buzzer
} else {
noTone(13); // Stop playing the tone
}
// Display pump status and mode on LCD
lcd.setCursor(5, 1);
lcd.print(pump ? "ON " : "OFF"); // Use ternary operator for conciseness
lcd.setCursor(9, 1);
lcd.print(digitalRead(11) ? "AUTO " : "MANUAL");
// Handle button presses for setting value and manual pump control
if (!digitalRead(10) && !state && digitalRead(11)) { // Set value button pressed in auto mode
state = 1;
set_val = inches; // Set new value based on current water level
EEPROM.write(0, set_val); // Save new value to EEPROM
} else if (!digitalRead(10) && !state && !digitalRead(11)) { // Set value button pressed in manual mode
state = 1;
pump = !pump; // Toggle pump manually
}
if (digitalRead(10)) // Button released
state = 0;
delay(500); // Wait for 500 milliseconds before the next loop
}
// Function to convert microseconds to inches
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2; // Conversion factor for ultrasonic sensor
}