While loop exit

Sorry if this has been asked before but I’m stuck, I’ve been through various docs, but most give examples based on exiting the loop through incrementation.

What I’m trying to achieve is yet another irrigation system, where it’s switched on at a set time which is working fine, but the “false” condition (when moisture1 is greater than thresholdValue) won’t trigger to exit the while loop.

Can I use while in this way?

#include <TimeLib.h>
#include <TimeAlarms.h>

int relaySwitch = 2;
int moistureSensor1 = A0;
int thresholdValue = 800;

AlarmId id;

void setup() {
  // put your setup code here, to run once:
   
  Serial.begin(115200);
  while (!Serial) ; // wait for Arduino Serial Monitor

  pinMode(moistureSensor1, INPUT);
  digitalWrite(relaySwitch, LOW);
  
  setTime(20,10,0,5,2,17); // set time to current

  // create the alarms, to trigger at specific times
  Alarm.timerRepeat(5, Repeats);           // timer for every 5 seconds just for testing for now

}

void loop() {

  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display

}

void Repeats() {

  int moisture1 = analogRead(moistureSensor1);
  while (moisture1 < thresholdValue){
    Serial.println("M1 Watering Plants");
    digitalWrite(relaySwitch, HIGH);
    
  }

Thanks in advance for any advice.

Ian

  while (moisture1 < thresholdValue){
    Serial.println("M1 Watering Plants");
    digitalWrite(relaySwitch, HIGH);
   
  }

Here is your while loop. Once the condition is met, what is supposed to make the while loop end? You do not need to turn the relay on over and over. You DO need to read the moisture sensor pin inside the loop, of you ever expect to terminate.

Wouldn’t your code make more sense if it said: if the moisure is below a desired level, turn on the water else leave things alone. (Is Repeats in the Alarm.timerRepeat(5, Repeats) call a pointer to function?) I assume so, otherwise there’s nothing to call the function. What if:

void Repeats() {

  int moisture1 = analogRead(moistureSensor1);

  if (moisture1 < thresholdValue) {                      // Need water?
     digitalWrite(relaySwitch, HIGH);                    // Yep, start watering...
     Serial.println("M1 Watering Plants");
     while (moisture1 < thresholdValue){                 // Keep watering until moisture is right
        moisture1 = analogRead(moistureSensor1);
     }
     digitalWrite(relaySwitch, LOW);                     // Done watering
  } 
    
}

Also, please read Nick Gammon’s post at the top of this Forum for tips on using this Forum, especially the use of code tags when posting code.

Thanks for your replies.

and thanks for your solution econjack, It's obvious now.

Sorry for the code posting, I've corrected it.