MultiWifi is a feature or technique used to allow the ESP32 to connect to multiple Wi-Fi networks. The idea is that the device can automatically switch between available Wi-Fi networks for better connectivity or reliability.
It is very useful if you need the ESP32 to automatically connect to Wi-Fi in different locations, like at the office and at home, without reconfiguring the Wi-Fi SSID and password each time.
Code
Here’s an example where the ESP32 can connect to multiple Wi-Fi networks. If it fails to connect to the first network, it will try to connect to the second, and so on:
#include <WiFi.h>
#include <WiFiMulti.h>
// Create an instance of WiFiMulti to handle multiple networks
WiFiMulti wifiMulti;
// Define your Wi-Fi credentials for multiple networks
const char* ssid_1 = "Network_1"; // First Wi-Fi network SSID
const char* password_1 = "Password_1"; // First Wi-Fi network password
const char* ssid_2 = "Network_2"; // Second Wi-Fi network SSID
const char* password_2 = "Password_2"; // Second Wi-Fi network password
void setup() {
// Start serial communication
Serial.begin(115200);
// Add Wi-Fi networks to WiFiMulti
wifiMulti.addAP(ssid_1, password_1);
wifiMulti.addAP(ssid_2, password_2);
Serial.println("Connecting to Wi-Fi...");
// Try to connect to the Wi-Fi networks
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
// Once connected, print the IP address
Serial.println("Connected to Wi-Fi!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Nothing to do in loop, ESP32 is connected to Wi-Fi
}
wifiMulti.addAP(ssid_1, password_1);
This line adds a Wi-Fi network (SSID and password) to the list of available networks that the ESP32 will attempt to connect to. When you call addAP, you’re telling the ESP32 to remember the Wi-Fi network details (SSID and password) so that it can try connecting to it later if needed.
wifiMulti.run()
wifiMulti.run(): This function tries to connect to the first available Wi-Fi network in the list. It continuously checks for a connection and returns the current connection status.
while (wifiMulti.run() != WL_CONNECTED)
ESP32 continuously tries to connect to a Wi-Fi network until a successful connection is made.