Wifi connection problem

Hello, I am developing a device using the ESP8266EX and am struggling with wifi connectivity issues. I am trying to write a code that meets the following conditions

  1. try to connect to multiple Wifi devices in sequence.
  2. If it fails to connect to any of them, it tries to connect again from the first one.
  3. If it connects to any of them, it stops trying to connect and stays connected to that wifi.
  4. Continue the above steps until a connection is established.

The code I have written is as follows

define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "XXX"
#define BLYNK_DEVICE_NAME "XXX"
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "XXX";
const char* ssidList[] = {"XXX", "YYY", "ZZZ"};
const char* passList[] = {"xxx", "yyy", "zzz"};

const int relay_output = 5;
BlynkTimer timer;
int input;
int safety;
int trigger;
int wait;

bool connectToWiFi() 
{
  while (WiFi.status() != WL_CONNECTED) 
  {
    for (int i = 0; i < sizeof(ssidList) / sizeof(ssidList[0]); i++) 
    {
      Serial.print("Connecting to ");
      Serial.println(ssidList[i]);
      
      WiFi.begin(ssidList[i], passList[i]);
      delay(5000); 
      if (WiFi.status() == WL_CONNECTED) 
      {
        Serial.println();
        Serial.print("Connected to ");
        Serial.println(ssidList[i]);
        return true;
      } 
      else 
      {
        Serial.println();
        Serial.print("Failed to connect to ");
        Serial.println(ssidList[i]);
      }
    }
    Serial.println("Retrying to connect to WiFi...");
  }
  return false;
}

BLYNK_WRITE(V0)
{
  trigger = param.asInt();
  if(safety==1 && trigger==1 && wait==0)
  {
    Serial.println("Signal Received!");
    digitalWrite(relay_output, HIGH);
    timer.setTimeout(500L, []() 
    {  
      digitalWrite(relay_output, LOW);
      wait = 1;
      timer.setTimeout(2000L, []() 
      {  
        wait = 0;
      });  
    }); 
  }
  else if(safety == 0 && trigger == 1)
  {
    Serial.println("Safety is ON!");
  }
}

BLYNK_WRITE(V1)
{
  safety = param.asInt();
  if(safety == 1)
  {
    Serial.println("Safety is unlocked!");
  }
  else
  {
    Serial.println("Safety is locked!");
  }
}

void setup()
{
  Serial.begin(115200);
  pinMode(relay_output, OUTPUT);

  if (connectToWiFi()) 
  {
    Blynk.begin(auth, WiFi.SSID().c_str(), WiFi.psk().c_str());
  } 
  else 
  {
    Serial.println("Could not connect to any WiFi network.");
  }
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED) 
  {
    Blynk.run();
    timer.run();
  } 
  else 
  {
    Serial.println("WiFi connection lost. Reconnecting...");
    connectToWiFi(); 
  }
}

When only one of the listed Wifis is available, I can’t connect to it. The Wifi router shows that the number of connections goes to 1 for a moment and then return to 0 immediately, so it seems that once connected, the connection does not continue and is immediately cut off. The serial monitor only repeats “Connecting to wifi name” and “Failed to connect to wifi name”.
I would appreciate it if you could tell me why the connection is not maintained and what I can do about it.

You’re only giving your device one 5 second chance to connect to WiFi here, which often doesn’t work.

This is a snippet of code from my routine, which checks 20 times, at 1 second intervals if it’s connected…

  wifi_attempt_count=0;
  
  Serial.println(F("Connecting to Wi-Fi..."));
    
  if (WiFi.status() != WL_CONNECTED)
  {
      WiFi.begin(ssid, pass); // connect to the network
  }

  while (WiFi.status() != WL_CONNECTED  && wifi_attempt_count < 20) // Loop until we've connected, or reached the maximum number of attemps allowed
  {
    delay(1000);
    wifi_attempt_count++;   
    Serial.print(F("Wi-Fi connection - attempt # "));
    Serial.print(wifi_attempt_count);
    Serial.println(F(" of 20"));
  }

  // we get to this point when either we're connected to Wi-Fi, or we've tried too many times. We need to do differnet things, depending which it is...
  if (WiFi.status() == WL_CONNECTED)
  {
    WiFi.mode(WIFI_STA);
    Serial.println(F("Wi-Fi CONNECTED"));
    Serial.println();
    // Do some more stuff in here....
   }

  else
  {
    // do some other stuff instead...
  }

This is what I see in my serial monitor…

19:52:56.523 -> Wi-Fi connection - attempt # 1 of 20
19:52:57.491 -> Wi-Fi connection - attempt # 2 of 20
19:52:59.254 -> Wi-Fi connection - attempt # 3 of 20
19:53:00.221 -> Wi-Fi connection - attempt # 4 of 20
19:53:00.253 -> Wi-Fi CONNECTED

In this case it connected after 4 attempts (4 seconds) but it can often take many more attempts.
It might be worth you trying this approach.

Pete.

Thank you very much for your reply.
There seemed to be two reasons for my problem above:

  1. insufficient delay time for establishing connections, as you pointed out
  2. something related to my smartphone.

When I tried the new code you suggested, I could establish the connection with my mobile router! However, the problem above

"The Wifi router shows that the number of connections goes to 1 for a moment and then return to 0 immediately, so it seems that once connected, the connection does not continue and is immediately cut off. "

still appears when I used my smartphone as the available router. Yesterday’s problem occurred in a same situation (and couldn’t connect to other routers maybe because of the insufficient delay time). Are there any ways that enables to use my smartphone like the mobile router?

Nevertheless, I will use mu mobile router in practice, so the current version is sufficient to use. I really appreciate for your help, and would appreciate it again if you could provide me further information on the remaining problem above.

Is your phone trying to force a 5GHz WiFi connection instead of allowing the 2.4GHz required by your board?
I know the later model iPhones do this by default, and that you need to change the hotspot settings to enable 2.4GHz.

Pete.

No, the current setting allows 2.4GHz connection.
This problem seems not to related to the sequential connection trial above because this phenomenon occurred even when I fixed the access point to my smartphone.