Why are loops not recommended inside loop function

So previously on this forum I have been advised not to use While loops inside the loop function and instead write code with if-else statements.

The thing is, sometimes, loops (while loop, for loop, etc.) make life much easier and the code easier to understand and debug.

My question is, is it absolutely too bad to use loops inside the loop function? What exactly could go wrong?

The proof of the pudding is in the eating.

it's not bad, it depends what you want the code to do.

your loop will take some time, meaning the system won't go back to the main function and perform some other work as often as if you had used an if. On some arduinos, if you are stuck for too long in a while loop, it might trigger the watchdog and reboot the arduino...

another example is if you test the state of a button at the start of the loop, and you have a long lasting while (blocking code basically) inside the loop, you won't come back and check the button again soon...

so that's why you got that advice - but it's a general recommendation, your mileage may vary. it's totally OK to have a short for or while loop within the loop() function

3 Likes

I have actually used loops inside loop function and never faced a problem. But since I have been advised against I am scared of continuing the practice, but I don't get why is this practice advised against.

Using while loops or for loops inside the loop() function will inevitably slow down how fast the code in the loop() function is repeated.

Suppose that you read the state of an input in the loop() function and need to do so frequently in order to detect an input and react to it, perhaps to prevent a moving object going too far along a track. Would you want that to be delayed by a while loop that takes a significant time to execute ?

Of course, this may not be relevant to your projects but it is good practice to program in a defensive way that will prevent future problems occurring

2 Likes

One approach, which seems to be popular, is to continue doing until you face a problem.

Which you will, sooner later. Once you are doing some more sophisticated or involved projects.

a7

3 Likes

It sounds like your definition of what looping is should be re-examined.

BTW, using while( ) can often block program execution until the while(…) fails to evaluate.

Example: if you use while(digitalRead(mySwitch) == LOW) {…}

The above stays right there until the switch goes HIGH, other code execution stops when the switch is LOW.

If the switch is LOW for 10 seconds, other code stops executing for 10 seconds.

1 Like

Imagine the flowchart on the left "thing 1" is "play with dog" and "thing n" is "feed cat".. everything gets needed attention and life is good.

Then, imagine the flowchart on the right with the same "thing1" and "thing n"... you would have one unhappy household.

3 Likes

No, it's not absolutely bad. The thing that's bad is blocking code. You have to look at the for loop or the while loop and consider how long it will take and do you want other things to happen during that time or not.

If I want to look through a char array and find the letter F then a for loop is just the thing.

char arr[] = "ABCDEFGHIJKLMNOP";
int indexOfF;
for (int i=0; i<sizeof(arr); i++){
  if(arr[i] == 'F'){
     indexOfF = i;
     break;
  }
}

That for loop will buzz through in no microseconds and the code will move on.

Now on the other hand if I want to move a servo:

for (int i = 0; i < 180; i++) {
    servo.write(i);
    delay(25);
}

That code is going to take a long long time to run through. It has to repeat 180 times and each one takes 25ms. What's worse is that it spends most of its time just waiting for the servo to move. If you've got lights to flash at the same time, then this is a big gap of time where your lights aren't being handled.

The idea is to not use for loops and while loops to wait on something to happen. If you've got the whole thing there and can get it done quickly then it's no problem. But don't stop the whole program to wait on a servo to finish moving.

UNLESS: you've really got nothing else to do. There are times where we actually want the rest of the program to stop while we do something. An example is on my robot I have a method to allow me to reprogram the EEPROM over the serial line. When I start that it drops into a while loop so that nothing else on the whole robot happens except for reading my data from serial and writing it to the EEPROM. That's intentional because I don't want anything else to happen during that time. So I wrote a big old blocking function with a while loop to stop everything else in its tracks and focus only on the one task.

So my final answer is that loops aren't bad in and of themselves. You just have to look at the particular loop you are building and think about how long it will block and whether or not you want to block for that length of time.

4 Likes

Till now I have used while loops only when I do not need anything else to be done. But because my while loop might be going on for like 7-19 seconds, and I have heard advises like the one given by @J-M-L quoted below, I am scared of using the While Loop even though its often the more attractive path (lines of code are significantly reduced with while loops). So maybe will just stick with if-else as an excess of caution.

You can only trigger a watchdog time out if you actually turn on the watch dog yourself. It won't happen by its self, it takes some setting up to get them going.

1 Like

I believe it’s on automatically for the software or hardware watchdog on esp8266 for example. So for portability it’s good to know about it.

Some API calls like delay() will pat the dog so you might not see it if you block a long time and call any of those functions.

You could test the SW watchdog on an ESP8266 See if that triggers a reboot

void setup() {
 while (true) ;
}

void loop(){}

You could test the HW watchdog on an ESP8266 if you disable the SW watchdog. See if that triggers a reboot

void setup() {
 ESP.wdtDisable();
 while (true) ;
}

void loop(){}
1 Like

Woul be glad to have (I had; but, I can't find it now) main() codes for UNO to see if WDT Timer is enabled or not?

it's not for the UNO

main.cpp is here

functions in #include <avr/wdt.h> will help you play with it ( wdt_enable(), wdt_reset(), wdt_disable())

reduced typing is a fools optimization.

Don't be scared. The antidote to fear is knowledge. Learn what the problems are. Learn WHY things can happen. Once you know and it's not a mystery then it won't be nearly as scary. You'll be able to predict whether or not it will be a problem.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.