Are sketches with a WiFi connection locked up in a "while" statement until communication is achieved?

If a processor never successfully connects with a local area network using a "while loop" does it prevent the rest of the sketch from ever executing? If so, do you need to have a way to "break" out of the loop and continuing executing the remainder of the program?

Serial.begin(115200);
 
    while (WiFi.status() != WL_CONNECTED)
    {
     Serial.println("Attempting to Connect To Local LAN:   ");
     Serial.println(wifissid); 
     WiFi.begin(wifissid, wifipass);
     delay(4000);
     Serial.print(".");
    }
     Serial.println("");
     Serial.print("Connected to WiFi network with IP Address: ");
     Serial.println(WiFi.localIP());
     Serial.println("Attempting to connect to WPA network...");

     server.begin();                 // added 2/4 testing
              // you're connected now, so print out the status:
     Serial.print("WiFi Status:  ");
     Serial.println(WiFi.status());
     Serial.println();
     Serial.print("ESP Board MAC Address:  ");
     Serial.println(WiFi.macAddress());

     startMillis = millis();  //initial start time for counter/timer
     DS18B20.begin();    // initialize the DS18B20 space sensor
    
    }                              
                                    // *********** VOID LOOP ************
     void loop()
     {
      DS18B20.requestTemperatures();              // send the command to get temperatures
      space_temp_1 = DS18B20.getTempCByIndex(0);  // read temperature in °C
      sp_temp_1F = (space_temp_1 * 9 / 5) + 32;   // convert C to F
      sp_temp_1 = sp_temp_1F + tmp_adj_1;         // sensor calibration
           
      digitalWrite(ONBOARD_LED,HIGH);             //  Blink for run indicator
      delay(300);
      digitalWrite(ONBOARD_LED, LOW);
      delay(1000);                       

To get out of the loop you need some additional test. A retry count or a timeout as part of the while test.What are you going to do in the rest of the code if there is no connection?

I have several buildings on my property that I want to install monitoring/control
processors in. As well as have them tied to my local LAN so I can get live status updates.
If the WiFi connection never connects or becomes lost after connecting I still want
the remainder of the sketches to function as usual. For instance in my wife's "She Shed"
there is a ventilation fan controlled by space temp. I still want that control process
functioning even if no WiFi connection exists.

You can probably do something like this to move the establishment of a connection to the loop().

void loop() {
. . .
   static uint32_t lastConnectionAttemptAtMs =  millis() ;  // static initialized Once only
   static bool restartFlag = false ;
   if (WiFi.status() != WL_CONNECTED && millis() - lastConnectionAttemptAtMs  > 15000ul ) {
       lastConnectionAttemptAtMs = millis() ;
       WiFi.begin(wifissid, wifipass);
       restartFlag = true ;
   } 
   if (WiFi.status() == WL_CONNECTED && restartFlag == true) {
       restartFlag = false  ;
       server.begin() ;
       // other initialization dependent on having a connection 
    }
. . . 
} 

EDIT
Corrected assignment operator (see post #20)

Here is a function that resets the ESP32 if there is no WiFi connection after so many attempts. A code change would bypass the rest.

void connectToWiFi()
{
  int TryCount = 0;
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
}

I have a separate task that runs 4 times a second that checks on the WiFi connection and if not connected calls connectToWiFi().

To gain some clarification on how things work in a LAN: does an ESP/UNO and the local router communicate continually once the microcontroller comes online and gets a LAN device address assignment ? Or is the microcontroller only polled when there is a request such as when I type in the address on my browser and get a webpage update?

I like your void call if the connection is lost.

What are you referring to here?

There is going on some communication on a low level that keeps the ESP-device connected over WiFi. But this is below what you can access and influence directly.

The rest of the communication depends on how do it.
You can setup your ESP-devices as clients or as servers.

For typing a IP-adress into your browser the ESP would act as a server (that delivers = serves a webpage)
And even this can be made in a way that you have to re-load the website to get an update or the ESP is updating the website in your browser once every second.

There are functions to get information about the connection-status

@Idahowalker if resetting the ESP is a good solution depends on the control-algorithm and if the controlled device is able to handle the situation of "no valid control signal" without going crazy or getting damaged.

Some ESP-IO-pins are pulled high some others are pulled low some act as PWM-output while booting.

best regards Stefan

This code as I originally posted,

void connectToWiFi()
{
  int TryCount = 0;
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
}

resets the ESP32 after 10 tries to connect with this line ESP.restart();. If you changed that line to say //ESP.restart();, the restart would not happen and you can have the code do other things instead of reset.

This does not exactly match the OP's requirement that the rest of the code should function even if no WLAN connection can be established. It is no doubt useful though in an application which is wholly dependent on a functioning WLAN.

Yea, sorry. I did not change my code to match the OP's requirements. The OP could though, right?

Gotcha...thanks... :+1:

Agreed. But for my purposes where I am controlling a vent fan in one building and
monitoring a domestic water line low pressure condition in another a restart would not critically
jeporadize anything.

:+1:

1 Like

Understood... my WiFi connections actually do both. I do one time polling of the processor for building data and I have alarm-based void statements that contact an API cloud server to let me know when things are awry.

With an ESP32 using WIFi, the WiFi code is put onto Core0 and the rest of the code is put onto Core1. The WiFi code runs completely independent of the user code. On a ESP32 the WiFi code is managed by freeRTOS. The most important thing freeRTOS does is to allow for the synchronized passing of messages from one core to the next.

WiFi.onEvent( WiFiEvent );

I read a little bit on this function over at dfrobot.com but was trying to understand the practical application. After the restart finishes does the processor return to this point and execute whatever is included inside the parentheses ( WiFiEvent)?
Finally is there a good Book For Dummies or website that explains web servers, clients, AP access points, APIs, etc? I want more than a cursory understanding but don't need to understand all the minutae needed for code level.

Does this "static" need to be defined outside the void loop() to be intialized only once?

No. You can leave it exactly as it is. It is simply a comment for those who may not understand that a static variable is initialised only once and not every loop iteration.

You can also do it like this instead if you prefer to make lastConnectionAttemptAtMs a global variable:

// globals
. . . 
uint32_t lastConnectionAttemptAtMs ;
. . .

void setup() {
  . . .
  lastConnectionAttemptAtMs = millis() ;
  . . .
}

thank you for the clarification. I learn something new every time I seek out information on this forum. :+1:

@edthewino Yes, you are of course correct (in your PM). This is a classic copy and paste error and the double equals operator is clearly wrong here:

Thanks for pointing it out and I will correct it in the original post.