/*
Forum: https://forum.arduino.cc/t/im-trying-to-make-an-automatic-watering-system-with-a-1602-i2c-lcd-a-relay-for-toggling-the-pump-and-a-capacitive-soil-moisture-sensor/1442240
Wokwi: https://wokwi.com/projects/462850559170269185
TO sketch with modifications
2026/05/01
ec2021
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int soilMoisturePin = A0;
const int BUTTON_PIN = 3;
const int RELAY_PIN = 7;
int sensorValue = 0;
int moisturePercent = 0;
constexpr unsigned long interval = 200; // Measure the moisture every 200 ms
unsigned long lastMeasurement = 0;
byte btnDown;
void setup()
{
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Zemlja ");
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(RELAY_PIN, OUTPUT);
}
void loop()
{
if (millis() - lastMeasurement >= interval) {
lastMeasurement = millis();
sensorValue = analogRead(soilMoisturePin);
sensorValue = constrain(sensorValue, 0, 1020);
moisturePercent = map(sensorValue, 0, 1020, 100, 0);
lcd.setCursor(0, 0);
lcd.print(moisturePercent);
lcd.print(" % ");
}
btnDown = !digitalRead(BUTTON_PIN);
if (moisturePercent < 40 || btnDown) {
WateringInProgress();
}
}
void WateringInProgress() {
if (btnDown) {
lcdPrint("Manual override");
} else {
lcdPrint("Watering ");
}
digitalWrite(RELAY_PIN, HIGH);
delay(3800);
digitalWrite(RELAY_PIN, LOW);
lcdPrint("Not watering ");
}
void lcdPrint(char* msg) {
lcd.setCursor(0, 1);
lcd.print(msg);
}