Little Bird Curriculum / code littlebird.com.au
vce_u1_07_watering.ino Arduino (C/C++) 57 lines · 2 views ✦ Open in English IDE Raw Download Embed view

Soil moisture in, pump out, with hysteresis and a maximum run time so a failed sensor cannot empty the reservoir.

From the unit VCE Systems Engineering Unit 1 — Electrotechnological systems design · activity PRP 7: Automatic watering — sensing, deciding, acting
// 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);
}

Embed this snippet

As an iframe:

Or drop it inline with a script tag (injects the highlighted block where included):

Shared from Little Bird Electronics curriculum.

Copied to clipboard