Search code examples
c++wifiesp32

ESP32 WiFi.status() always returns WL_DICSONNECTED (STA_MODE)


I've spent a many hours trying to solve this.

I have added multiple attempts, tried to WiFi.disconnect() before Wifi.begin(). Nothing works: statusremains to be WL_DISCONNECTED (0x06).

WiFi.mode(WIFI_STA);
for(;;) {
        attempt++;

        Wifi.begin(ssid, password);
        wl_status_t status = WiFi.status();
        String m = connectionStatusMessage(status);
        log("Connection attempt %d: status is%s", attempt, m.c_str());

        if (status == WL_CONNECTED) {       
            Serial.println();
            success("connected (WL_CONNECTED)");
            information();
            break;
        } 

[UPDATE] Note: I use a ESP-WROOM-32 devkit package. The ESP32 sdk being the latest stable available on PlatformIO. I tested others devkits such a one from Az-Delivery too.


Solution

  • I finally found a solution: The fix is to use WiFi.waitForConnectResult() instead of WiFi.status().

    I initially thought it was a bug but as @juraj mentioned, and by examinination of the WiFi code, it is a matter of waiting for the status to come. And the waitFoConnectionResult() does just that. Hence the result.

    Working code as follows:

       WiFi.mode(WIFI_STA);
       for(;;) {
            attempt++;
    
            Wifi.begin(ssid, password);
    
            // >>>> the fix <<<<<
            uint8_t status = WiFi.waitForConnectResult();
    
            String m = connectionStatusMessage(status);
            log("Connection attempt %d: status is%s", attempt, m.c_str());
    
            if (status == WL_CONNECTED) {       
                Serial.println();
                success("connected (WL_CONNECTED)");
                information();
                break;
            }