#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Pin definitions
const int potPin = A0; // Potentiometer pin
const int servoPin = 9; // Servo control pin
const int switchPin = 8; // Slide switch pin
const int redPin = 10; // Red pin of RGB LED
const int greenPin = 11; // Green pin of RGB LED
Servo waterValve;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Initializing servo and LCD
waterValve.attach(servoPin);
lcd.begin(16,2); // Initializing the I2C LCD
lcd.backlight(); // Turning on the backlight
lcd.print("Valve Opening:");
// Setting the switch pin mode
pinMode(switchPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
// Turn off the RGB LED initially
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
}
void loop() {
if (digitalRead(switchPin) == HIGH) { // If switch ON
// Read potentiometer value (0-1023)
int potValue = analogRead(potPin);
int servoAngle = map(potValue, 0, 1023, 0, 180); // mapping servo angle to % value
waterValve.write(servoAngle); // Setting servo position
// Calculate the percentage of valve opening
int percentage = map(servoAngle, 0, 180, 0, 100);
// Displaying percentage on LCD
lcd.setCursor(0, 1); // Move to the second line
lcd.print(percentage);
lcd.print("% "); // Extra spaces to clear previous values
// Turning on green LED
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
} else {
// If switch OFF, turn off servo and clear display
waterValve.write(0); // Closing valve
lcd.setCursor(0, 1);
lcd.print("System OFF ");
digitalWrite(redPin, HIGH); // turining on red LED
digitalWrite(greenPin, LOW); // Turn off green LED
}
delay(100); // Delaying for stability
}