// PRP 7 — automatic watering.
//
// Pump is driven through a motor driver module, NOT directly from a pin.
// A board pin supplies tens of milliamps; the pump wants hundreds.
//
// MAX_RUN_MS is the safety limit. If the sensor falls out of the soil or
// fails open, an unlimited pump empties the reservoir onto the bench.
// A control system that cannot fail safely is not finished.
const int MOISTURE_PIN = A0;
const int PUMP_PIN = 9; // to the driver module input
const int DRY_BELOW = 400; // <-- your calibrated numbers
const int WET_ABOVE = 600;
const unsigned long MAX_RUN_MS = 15000UL; // never pump longer than this
const unsigned long REST_MS = 60000UL; // let water soak in before re-reading
bool pumping = false;
unsigned long pumpStartedAt = 0;
unsigned long pumpStoppedAt = 0;
void setup() {
pinMode(PUMP_PIN, OUTPUT);
digitalWrite(PUMP_PIN, LOW);
Serial.begin(9600);
}
void loop() {
int moisture = analogRead(MOISTURE_PIN);
unsigned long now = millis();
if (pumping) {
bool wetEnough = moisture > WET_ABOVE;
bool runTooLong = (now - pumpStartedAt) >= MAX_RUN_MS;
if (wetEnough || runTooLong) {
digitalWrite(PUMP_PIN, LOW);
pumping = false;
pumpStoppedAt = now;
if (runTooLong) {
Serial.println("STOPPED ON RUN LIMIT - check the sensor");
}
}
} else {
bool dry = moisture < DRY_BELOW;
bool rested = (now - pumpStoppedAt) >= REST_MS;
if (dry && rested) {
digitalWrite(PUMP_PIN, HIGH);
pumping = true;
pumpStartedAt = now;
}
}
Serial.println(moisture);
delay(500);
}