ESP32 does not connect to WiFi if the connection fails the first time

With ESP32, I have these functions:

// try to connect
void Network::goStation()
{
    Serial.print(F("[NET] Try to connect to:"));
    Serial.println(wifiConfig.WiFi_Creds.wifi_ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(wifiConfig.WiFi_Creds.wifi_ssid, wifiConfig.WiFi_Creds.wifi_pw);
    if (WiFi.waitForConnectResult(5000) == WL_CONNECTED)
    {
        Serial.print(F("[NET] Connected to: "));
        Serial.println(WiFi.SSID());
        Serial.print(F("[NET] Local IP: "));
        Serial.println(WiFi.localIP());
        _mode = Modes::Station;
    }
    else goRetry();
}

// called after a failure
void Network::goRetry()
{
    Serial.println(F("[NET] Connection failed. Retry in 60 s"));
    WiFi.disconnect();
    _timeRef = millis();
    _mode = Modes::Retry;
}

I have an FSM to handle the different cases, I don't report all the code here since the machine itself is working (I mean the functions above are called as expected).

On power up I try to connect to the WiFi:

goStation();

Once connected, I check for disconnections:

if (WiFi.status() != WL_CONNECTED) goRetry();

and after 1 minute I call again goStation().

If on power up the WiFi network is available:

  1. it connects successfully with goStation()
  2. after some time I turn off my router
  3. it detects the failure and calls goRetry()
  4. I turn on the router
  5. after 1 minute, it calls again goStation() and connects as expected

So far, so good. But, If on power up the WiFi network is NOT available:

  1. it fails the first connection in goStation() and calls goRetry()
  2. I turn on my router
  3. every minute it tries to connect calling goStation() but it always fails

The only way I found to connect again is to reset the MCU.

Do you see any evidence of errors in my code? Why if it does not connect the first time, it never connects?

Thanks but it makes no sense to restart the MCU just to try to reconnect. I have a lot of other stuff to control. I really cannot reset the MCU as workaround.

I have the WiFi.disconnect(); call in my goRetry() function.
I can try to add it also in goStation() but on power up it should be not necessary.

OK, well I tried. Good luck.

Simplest solution would be to set a flag that if the connection fails the first time, rather than calling

goRetry();

you call

goStation();

unitl you have connected successfully at least once.

In fact the best way to do this is to first check and see if the network you are intending to connect to actually exists. Why bother trying to connect to a network that is not even available.

I start out with a netscan, and compare the result with stored networks and go from there.

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