// The soil sensor's analog output and // its supply, on only while it reads const int SOIL_PIN = A0; const int SENSOR_POWER = 7; // The relay module's IN pin const int RELAY_PIN = 8; // Most relay modules switch on LOW; if // yours switches on HIGH, swap the two const int RELAY_ON = LOW; const int RELAY_OFF = HIGH; // Calibration: raw readings with the // sensor in dry air and in water const int DRY_RAW = 1023; const int WET_RAW = 300; // Watering starts below this and stops // once past this (percent) const int DRY_LIMIT = 30; const int WET_LIMIT = 50; // How long the pump runs per watering const unsigned long PUMP_TIME = 3000; // Wait for the water to soak in const unsigned long SOAK_TIME = 30000; // Time between readings (ms) const unsigned long CHECK_EVERY = 10000; // If the soil is still dry after this // many waterings, the tank is empty const int MAX_PUMPS = 5; bool watering = false; int pumps = 0; void setup() { // Write "off" first, so the pump never // runs even for a moment at start-up digitalWrite(RELAY_PIN, RELAY_OFF); pinMode(RELAY_PIN, OUTPUT); pinMode(SENSOR_POWER, OUTPUT); pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); Serial.println("Automatic watering started."); } // Sensor on, mean of 5 readings, off: // this way the probes corrode slowly int readRaw() { digitalWrite(SENSOR_POWER, HIGH); delay(100); long total = 0; for (int i = 0; i < 5; i++) { total += analogRead(SOIL_PIN); delay(10); } digitalWrite(SENSOR_POWER, LOW); return total / 5; } void runPump() { digitalWrite(RELAY_PIN, RELAY_ON); delay(PUMP_TIME); digitalWrite(RELAY_PIN, RELAY_OFF); } // The tank may be empty: the pump stays // off and the on-board LED blinks void stopForGood() { Serial.print(MAX_PUMPS); Serial.println(" waterings and the soil is still dry: the tank may be empty or the hose out of the pot."); Serial.println("Pump stopped. Check it, then press reset."); while (true) { digitalWrite(LED_BUILTIN, HIGH); delay(300); digitalWrite(LED_BUILTIN, LOW); delay(300); } } void loop() { int raw = readRaw(); // Close to 0: the sensor has no power if (raw < 50) { Serial.print("Cannot read the sensor (raw "); Serial.print(raw); Serial.println("), check the wires."); delay(CHECK_EVERY); return; } // Dry soil reads high, wet soil low int moisture = constrain(map(raw, DRY_RAW, WET_RAW, 0, 100), 0, 100); Serial.print("Moisture: "); Serial.print(moisture); Serial.print("% (raw "); Serial.print(raw); Serial.println(")"); // Two thresholds: no flicker at edge if (!watering && moisture < DRY_LIMIT) { watering = true; pumps = 0; Serial.println("Soil is dry, watering starts."); } if (watering && moisture >= WET_LIMIT) { watering = false; Serial.println("Soil is moist, watering done."); } if (watering) { if (pumps >= MAX_PUMPS) { stopForGood(); } runPump(); pumps++; Serial.print("Pump ran ("); Serial.print(pumps); Serial.println("), water soaking in..."); delay(SOAK_TIME); return; } delay(CHECK_EVERY); }