I have devised a sketch were I can connect to the first available WiFi network of a list of possible WiFi networks.
The sketch goes testing one by one and when it finds an available WiFi network it tries to connect to it.
It works fine.
But when it has to go one WiFi network after the other it takes some time.
So I devised a way to store the first index of the network list that works for, if the connection has to be restored, it should try to connect with that network in the first place before trying all those that remain on the list.
The problem is that by using the stored index the command "WiFi.begin(" fails to "see" the credentials for login and the connection fails leading the next if and to try the whole list once again.
On the beginning of the sketch I have:
const char* mySSID[] = {"net1","net2","net3"};
const char* myPASS[] = {"pass1","pass2","pass3"};
static byte goodWiFi=0;
So as the system boots gooWiFi = 0, what means the function below will start from net1 and try the list one by one till connection succeeds.
At any moment the sketch can call the function below to check it WiFi connection is ok, if not it will reconnect:
void connectWiFi(){
if(goodWiFi!=0 && (WiFi.status() != WL_CONNECTED)){
WiFi.mode(WIFI_STA);
WiFi.begin(mySSID[goodWiFi], myPASS[goodWiFi]);
Serial.print(newLine + "IP address: ");
Serial.println(WiFi.localIP());
if(WiFi.status() == WL_CONNECTED){
return;
}
}
if(WiFi.status() != WL_CONNECTED){
for(int i=0;i<sizeof(mySSID);i++){
WiFi.mode(WIFI_STA);
WiFi.begin(mySSID[i], myPASS[i]);
Serial.println(newLine + "Connecting Wifi: " + String(mySSID[i]));
long StartTime=millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if ((StartTime+3000) < millis()) break;
}
if(WiFi.status() == WL_CONNECTED){
Serial.print(newLine + "IP address: ");
Serial.println(WiFi.localIP());
goodWiFi = i;
Serial.print("GoodWiFi set to: ");
Serial.println(goodWiFi);
return;
} else {
Serial.print(" Failed.");
}
}
}
Serial.println("No WiFi connection. Reset");
delay(1000);
ESP.restart();
}
If goodWiFi = 0 everything works ok and the Sketch will connect in the first network that responds (and credentials match) and it will store i that is the index of the network that worked in the variable goodWiFi.
Suppose the WiFi network that succeeded to connect was net2, the value stored in i will be 1.
If the function connectWiFi() is called again and i=1 the first if above will run and the command:
WiFi.begin(mySSID[goodWiFi], myPASS[goodWiFi]);
Will run and, supposedly, the sketch will connect straight with a WiFi network known to be available reducing the connection delay.
That is theoretically because when goodWiFi != 0 the connection never takes place and
Serial.println(WiFi.localIP());
always return 0.0.0.0 and the sketch goes on to the next if to scan the entire list again!
It behaves as if mySSID[goodWiFi] and myPASS[goodWiFi] were empty but this is not the case, I tested.
Thanks