#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the pins for the ultrasonic sensor, LED, relay module, and push button
#define TRIG_PIN 26
#define ECHO_PIN 25
#define LED_PIN 27
#define RELAY_PIN 27
#define BUTTON_PIN 32 // Push button pin
// Define the I2C address of the LCD display
#define LCD_ADDR 0x27
// Initialize the LCD display
LiquidCrystal_I2C lcd(LCD_ADDR, 16, 2);
// Variables to store the state of the button and the manual override
bool manualOverride = false;
bool buttonState;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
float lastDistance = 0; // Track the last measured distance
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
lcd.init();
lcd.backlight();
lcd.print("Water Level");
delay(2000); // Display welcome message for 2 seconds
lcd.clear();
}
void loop() {
// Read the push button state with debounce
bool reading = digitalRead(BUTTON_PIN);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
manualOverride = !manualOverride;
Serial.println("Button Toggle");
lcd.clear();
lcd.print("Manual Toggle");
delay(1000); // Display message for 1 second
}
}
}
lastButtonState = reading;
// Send a trigger pulse to the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the time it takes for the echo pulse to return
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance to the water surface
float distance = duration * 0.034 / 2;
// Automatically reset manual override if the water level crosses the threshold
if ((lastDistance < 50 && distance >= 50) || (lastDistance >= 50 && distance < 50)) {
manualOverride = false;
Serial.println("Auto Reset");
}
lastDistance = distance; // Update lastDistance for the next cycle
// Update the LCD with the current distance
lcd.clear();
lcd.print("Dist: ");
lcd.print(distance, 1);
lcd.print("cm");
// Automatic control based on water level
if (!manualOverride) {
if (distance < 50) {
digitalWrite(LED_PIN, LOW); // Turn off LED
digitalWrite(RELAY_PIN, HIGH); // Turn off motor
lcd.setCursor(0, 1);
lcd.print("Motor OFF");
} else {
digitalWrite(LED_PIN, HIGH); // Turn on LED
digitalWrite(RELAY_PIN, LOW); // Turn on motor
lcd.setCursor(0, 1);
lcd.print("Motor ON");
}
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED
digitalWrite(RELAY_PIN, HIGH); // Turn off motor
lcd.setCursor(0, 1);
lcd.print("Manual OFF");
}
// Wait for a second before taking the next measurement
delay(1000);
}