#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4); // Initialize LCD with I2C address 0x27, 20 columns, 4 rows
const int relayPin = 26; // GPIO pin to which the relay is connected
void setup() {
Wire.begin(23, 22); // Initialize I2C communication with SDA 23 and SCL 22
Serial.begin(9600); // Initialize Serial communication at 9600 baud rate
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
pinMode(relayPin, OUTPUT); // Set the relay pin as an output
digitalWrite(relayPin, HIGH); // Initially turn the relay OFF (HIGH means OFF for active-low relay)
}
void loop() {
// Step 1: Read soil moisture value from the sensor
int16_t moistureValue = analogRead(34); // Read the analog value from moisture sensor
// Step 2: Determine the moisture status based on the sensor value
String moistureStatus = (moistureValue < 30) ? "DRY" : (moistureValue > 70) ? "WET" : "OK";
// Step 3: Control the relay (pump) based on the soil moisture reading
if (moistureValue < 30) {
// Soil is dry, turn on the pump (relay on)
digitalWrite(relayPin, LOW); // LOW activates the relay for active-low relays
} else {
// Soil is not dry, turn off the pump (relay off)
digitalWrite(relayPin, HIGH); // HIGH deactivates the relay
}
// Step 4: Display on the LCD
lcd.clear(); // Clear the LCD before displaying new content
lcd.setCursor(0, 0); // Set cursor to the first line
lcd.print("Moisture: ");
lcd.print(moistureValue); // Display actual moisture value
lcd.setCursor(0, 1); // Move cursor to the second line
lcd.print("Status: ");
lcd.print(moistureStatus); // Show "DRY", "OK", or "WET" on the LCD
lcd.setCursor(0, 2); // Move cursor to the third line
lcd.print("Pump: ");
lcd.print(moistureValue < 30 ? "ON " : "OFF "); // Display pump status
delay(1000); // Wait for 1 second before the next loop iteration
}