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
- try to connect to multiple Wifi devices in sequence.
- If it fails to connect to any of them, it tries to connect again from the first one.
- If it connects to any of them, it stops trying to connect and stays connected to that wifi.
- 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.