#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define SOIL_SENSOR_PIN A0
#define RELAY_PIN 2
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 cols, 2 rows
void setup() {
pinMode(SOIL_SENSOR_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Motor OFF initially
lcd.begin(16, 2); // <- FIXED HERE
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Desert Farming");
lcd.setCursor(0, 1);
lcd.print("System Starting");
delay(2000);
lcd.clear();
}
void loop() {
int sensorValue = analogRead(SOIL_SENSOR_PIN);
// Convert analog value (0–1023) to percentage (0–100)
int moisturePercent = map(sensorValue, 1023, 0, 0, 100);
moisturePercent = constrain(moisturePercent, 0, 100); // Limit range
lcd.setCursor(0, 0);
lcd.print("Moisture: ");
lcd.print(moisturePercent);
lcd.print("% ");
if (moisturePercent < 20) {
digitalWrite(RELAY_PIN, HIGH); // Pump ON
lcd.setCursor(0, 1);
lcd.print("Soil Dry:Mot_ON");
}
else if (moisturePercent > 60) {
digitalWrite(RELAY_PIN, LOW); // Pump OFF
lcd.setCursor(0, 1);
lcd.print("Soil Wet:Mot_OFF");
}
else {
// Mid-range: optional keep motor status unchanged or off
digitalWrite(RELAY_PIN, LOW);
lcd.setCursor(0, 1);
lcd.print("Soil OK:Mot_OFF ");
}
delay(2000);
}