Menu
CoddyTech

Plant Monitor: Dry Alarm

Part of the Projects section of Coddy's Arduino journey. Lesson 19 of 24.

When the soil stays dry, the monitor calls for help with the buzzer on pin 8. Not at once: a reading can dip for a moment, and an alarm that goes off for nothing soon gets ignored. The rule is dry for more than 5 seconds (a real plant would wait hours).

To know how long the soil has been dry, note the moment it became dry. That needs one more piece of memory: whether it was dry at the last reading.

if (moisture < 30) {
  if (wasDry == false) {
    wasDry = true;
    dryStart = millis();   // it just became dry
  }
  if (millis() - dryStart > 5000) {
    tone(buzzerPin, 880, 200);
  }
} else {
  wasDry = false;
}

The else matters: when the soil is watered, wasDry goes back to false, so the next dry spell is timed from its own start.

loop() reads once a second, so the 200 ms beep sounds once a second while the soil stays dry.

challenge icon

Challenge

Medium

Add the dry alarm:

  • remember whether the soil was dry (bool wasDry) and when it became dry (unsigned long dryStart)
  • once it has been dry for more than 5000 ms, play tone(buzzerPin, 880, 200) after each reading
  • when it is 30% or more, set wasDry back to false

Press Run, turn the knob down and wait, then Check.

Try it yourself

// The knob stands in for a soil moisture sensor
const int sensorPin = A0;
// The status light: an RGB LED
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 6;

// The moisture in percent: 0 is bone dry, 100 is soaking wet.
int readMoisture() {
  int reading = analogRead(sensorPin);
  return map(reading, 0, 1023, 0, 100);
}

// Red when dry, green when it is fine, blue when wet.
void showStatus(int moisture) {
  digitalWrite(redPin, LOW);
  digitalWrite(greenPin, LOW);
  digitalWrite(bluePin, LOW);
  if (moisture < 30) {
    digitalWrite(redPin, HIGH);
  } else if (moisture <= 70) {
    digitalWrite(greenPin, HIGH);
  } else {
    digitalWrite(bluePin, HIGH);
  }
}

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int moisture = readMoisture();
  Serial.print("Moisture: ");
  Serial.print(moisture);
  Serial.println("%");
  showStatus(moisture);
  delay(1000);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Arduino playground