#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
const int trigPin = 3; // Ultrasonic sensor trigger pin
const int echoPin = 2; // Ultrasonic sensor echo pin
const int servoPin = 9; // Digital pin for servo motor
Servo myservo; // create servo object to control the servo
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 20 columns, 4 rows
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.attach(servoPin);
lcd.init(); // Initialize LCD
lcd.backlight(); // Turn on the backlight
}
void loop() {
float distance = measureDistance();
// Display information on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
// Check the distance threshold to close the valve
if (distance <= 25) {
closeValve();
} else {
openValve();
}
delay(1000); // Adjust delay based on your project requirements
}
void openValve() {
myservo.write(0); // Open the valve position
}
void closeValve() {
myservo.write(90); // Close the valve position
}
float measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return pulseIn(echoPin, HIGH) * 0.034 / 2;
}