#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the pins for the Ultrasonic Sensor
const int trigPin = 2;
const int echoPin = 3;
// Define the pins for the Relay Switch
const int relayPin = 4;
// Define the pins for the LEDs
const int greenLedPin = 5;
const int redLedPin = 6;
// Define the variables for the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
// Set the pins for the Ultrasonic Sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the pins for the Relay Switch
pinMode(relayPin, OUTPUT);
// Set the pins for the LEDs
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
// Set the initial state of the Relay Switch
digitalWrite(relayPin, LOW);
}
void loop() {
// Measure the distance using the Ultrasonic Sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
float duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// Turn on the green LED and start pumping water if the distance is greater than 7cm
if (distance > 7) {
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, LOW);
digitalWrite(relayPin, HIGH);
}
// Turn off the red LED and stop pumping water if the distance is less than 3cm
else if (distance < 3) {
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH);
digitalWrite(relayPin, LOW);
}
// Keep the state of the Relay Switch until the distance reaches 7cm again
else {
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, LOW);
}
}