How to include delay in while loop

I’m on a steep learning curve regarding delays while waiting for input from sensors, so this very basic question may seem dumb.
I understand the while loop() executes code inside the parentheses until the specified condition becomes true or false, but I cannot figure out how to write a delay routine inside the parentheses that causes my sketch to wait until the while condition changes.
Does anyone know of a simple delay routine to suit that purpose?

#1. Do not use delay(); you will thank everyone who says that, later.
#2. If you want to poll a sensor at a preset interval, use millis();

unsigned long timer, interval = 1000; // timer keeper, interval of 1 second

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (millis() - timer > interval) { // program running longer than "interval"
    timer = millis(); // store new "time zero"
    Serial.print("Hello. ");
    Serial.println(millis()/1000);
  }
}
2 Likes
  • And don’t use while( ) loops unless they are guaranteed to finish quickly.

  • You should also study up on how using the State Machine technique can make your programs flow smoothly.

3 Likes

The loop function loops. As others have suggested, while() can get beginners into trouble.

2 Likes

Please show your best-effort code.

Did you check the while reference:

and its example:

var = 0;
while (var < 200) {
  // do something repetitive 200 times
  var++;
}

With while(...){...}, the code within the parentheses () is tested and the code within the curly braces {} is executed repeatedly until the test fails. If the while condition is true, it should endlessly stay in the loop until the condition changes. One common error folks have is not changing the variables in the condition within the curly braces and expecting the condition to change. In the above, the while loop will delay until var++ repeats enough to get to 200. If the var++ wasn't in the curly braces, it would delay forever.

But it is often better to use if(...){...} instead of while(...){...} and let the loop(){...} function do all the looping for you.

2 Likes

Some reading; there are more articles on this site and on the web.

The first part of the sentence does not fit with the second. If you really understand how while works, it should be obvious to you that in order for the code to wait for a condition to be satisfied, the while loop does not need any delay. That's exactly what the while designed for - to wait in the loop until its condition is met.
It seems to me that you have not clearly formulated what exactly you need and what your problem is. Try again

Many thanks everyone. I can see how to xfpd’s suggestion can work in my case.