Page 1 of 1

WiFi.begin(ssid, password) and timeout

Posted: Sun Apr 11, 2021 5:39 pm
by CompilerError
Hello!
Quick question:

When does WiFi.begin(ssid, password) actually timeout when not able to connect?

I 'solved' the the 'problem' with the following code but find it not very elegant.

  1.    while (WiFi.status() != WL_CONNECTED && (millis() - startTime) <= 5000) // try for 5 seconds
  2.       {
  3.         delay(500);
  4.         Serial.print(".");
  5.       }

Re: WiFi.begin(ssid, password) and timeout

Posted: Mon Apr 12, 2021 11:05 pm
by gfreund
If it works in your code flow you can simply turn on asynchronous notifications and get the connection status from there. That also has the advantage that you can trigger re-connect attempts in case the WiFi network temporarily goes down. The basic logic is below. There are also tons of additional events you might want to process

Code: Select all

void wifiSetup() {
  WiFi.onEvent(onWiFiEvent);
}

void wifiConnect() {
  WiFi.begin("YourSSID", "YourPassword");
}

void onWiFiEvent(WiFiEvent_t event) {
  switch (event) {
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.print("WiFi begin failed ");
      // try reconnect here (after delay???)
      break;
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.print("WiFi begin succeeded ");
      // Connected successfully
      break;
    default:
       // Display additional events???      
  }
}

Re: WiFi.begin(ssid, password) and timeout

Posted: Tue Apr 13, 2021 12:33 pm
by CompilerError
Thank you ....

With WiFi.begin("YourSSID", "YourPassword") I'm generally wondering if the ESP32 will try to connect indefinitely?
So is this some kind of background task running forever if unsuccessful?

Also is there a documentation for the WiFi Class / Methods?
WiFiClass.JPG
WiFiClass.JPG (24.51 KiB) Viewed 15516 times

Re: WiFi.begin(ssid, password) and timeout

Posted: Tue Apr 13, 2021 8:20 pm
by gfreund
You're correct. The ESP32 will periodically send a SYSTEM_EVENT_STA_DISCONNECTED event if either the initial connection fails or the WiFi goes down. You can easily test it by "connecting" to a non-existing network and Serial.print() the event.

~G

Re: WiFi.begin(ssid, password) and timeout

Posted: Thu Apr 15, 2021 8:58 am
by CompilerError
Thank you,

How would I stop that WiFi.begin 'connect task' ?

It seems to me the ESP32 is quite eager to being connected to the internet/network ..

Re: WiFi.begin(ssid, password) and timeout

Posted: Thu Apr 15, 2021 10:43 pm
by gfreund
WiFi.disconnect()
~G

Re: WiFi.begin(ssid, password) and timeout

Posted: Mon Apr 19, 2021 9:41 am
by CompilerError
:)

Thank you!