Automatic Plant Watering System

Figure 1: Circuit diagram
Figure 1: Circuit diagram

Parts list

Components from Elegoo UNO R3 Ultimate Starter Kit:

Additional:

Arduino source code


int moistureSensorPowerPin = 7;
int motorPowerPin = 8;

int moistureSensor = 0;

void setup() {

    // Set the motor and moisture sensor control pins as
    // output pins and disable.
    pinMode(motorPowerPin, OUTPUT);
    digitalWrite(motorPowerPin, LOW);
    pinMode(moistureSensorPowerPin, OUTPUT);
    digitalWrite(moistureSensorPowerPin, LOW);

    //  setup serial
    Serial.begin(9600);              
}

void loop() {

    // Ensure the moisture sensor capacitor has sufficiently
    // discharged before we do anything.
    while (analogRead(moistureSensor) > 6) {
      delay(100);
    }

    int val = 0;
    int vc = 0;
    int vt = 0;
    
    digitalWrite(moistureSensorPowerPin, HIGH);
    
    // Read the moisture sensor until we get 40 readings
    // in a row that don't differ by more than 1 to ensure
    // the capacitor has settled down.
    while (vc < 40) {
    
        vt = analogRead(moistureSensor);     

        int diff = vt - val;
        if (diff < 0) diff = -diff;
        
        if (diff > 1) {
            vc = 0;
            val = vt;
        } else {
            vc++;   
        }
        
        delay(100);
        
    }

    // Write sensor value to serial for debugging
    Serial.println(val); 

    if (val > 420) {
    
        // If sensor value exceeds threshold, turn on motor
        digitalWrite(motorPowerPin, HIGH);
        
        // and wait until sensor value drops below lower threshold.
        while (val > 410) {
            val = analogRead(moistureSensor);
            Serial.println(val);
            delay(100);
        }
        digitalWrite(motorPowerPin, LOW);
    }
    
    // Disable moisture sensor to limit corrosion while not in use.
    digitalWrite(moistureSensorPowerPin, LOW);

    // wait 3 hours between readings
    delay(10800000);

}