#include <LiquidCrystal_I2C.h>
// Initialize the library with the numbers of the interface pins
LiquidCrystal_I2C lcd(0x27, 20, 4);
const int potentiometerPin = A0; // Potentiometer connected to analog pin A0
const int relayPin = 7; // Relay connected to digital pin 7
const int ledPin = 3; // LED connected to digital pin 3
int moistureLevel = 0;
const int moistureThresholdLow = 50; // Threshold for low moisture level
const int moistureThresholdHigh = 75; // Threshold for high moisture level
unsigned long previousMillis = 0; // will store last time the moisture was updated
const long interval = 1000; // interval at which to update the moisture reading (10 seconds)
void setup() {
// Set up the LCD's number of columns and rows:
lcd.init();
lcd.backlight();
pinMode(relayPin, OUTPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(relayPin, LOW); // Start with the sprinkler off
digitalWrite(ledPin, LOW); // Start with the LED off
}
void loop() {
// Get current time
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you updated the moisture level
previousMillis = currentMillis;
// Read the value from the potentiometer
moistureLevel = analogRead(potentiometerPin);
// Map the potentiometer value to a percentage (0 - 100)
int moisturePercentage = map(moistureLevel, 0, 1023, 0, 100);
// Clear the LCD and set the cursor to the beginning
lcd.clear();
lcd.setCursor(0, 0);
// Display the current simulated moisture level
lcd.print("Moisture: ");
lcd.print(moisturePercentage);
lcd.print("%");
// Check if moisture level is too low or too high
if (moisturePercentage < moistureThresholdLow || moisturePercentage > moistureThresholdHigh) {
lcd.setCursor(0, 1);
lcd.print("Sprinkler Activated!");
digitalWrite(relayPin, HIGH); // Turn on the relay
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(relayPin, LOW); // Turn off the relay
digitalWrite(ledPin, LOW); // Turn off the LED
}
}
}