if (!MDNS.begin("esp8266")) {
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
I know this will result in an infinite loop if the if
conditional is never satisfied, however I was wondering if this code would still result in an infinite loop if say, after 3 iterations the if
conditional is satisfied?
Or if something like:
while(!MDNS.begin("esp8266")) {
delay(1000);
}
is different?
Code from: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino (line 58)
2 Answers 2
This is likely a case where the original code needs to be inspected to understand the purpose of the infinite loop. In the original code we see this:
if (!MDNS.begin("esp8266")) {
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
Here, it can be inferred the infinite loop is used to preserve the error message on the serial monitor. By doing so prevents subsequent messages from announcing the Domain Name Server has started. Which may confuse the user.
As mentioned in other answers, infinite loops are often used to purposely reset a processor. However, this approach depend on an actively running watch dog feature. A feature that is not normally active or even supported in the Arduino development environment. Perhaps because the watch dog feature is considered an intermediate to advanced topic.
In the first case, the first time, that the outer if statement becomes true, the code will go into the while(1)
loop and will be stuck there forever.
The second code is different, since the while
loop will check at each start of it's iteration, if the condition is still met. If not, it will exit, so not necessarily an infinite loop.
Going into an infinite loop, if something fails to initialize is often done in the microcontroller world, especially when initializing external hardware. A reset loop (restarting until it works) is mostly not fitting there, because often it is not just waiting for a resource to become free. Often this is used for serious problems, for example external hardware not being there or functioning. Imagine trying to use an external GPS chip, but the chip is not there. It should be there, since the device is build this way. Why should a reset loop be better here? The problem won't get away with time. Or imagine, that the initialization fails, because the GPS chip is broken. Trying to interface such a broken chip repeatedly might break even more things. Either way, someone has to look at this, to fix the problem. It will not go away by itself.
I would say, that the failed initialization in the library above is such a situation.
if
condition could be satisfied more than once?if(condition) { while(1) }
the same aswhile(conditional) { }