ESP32 WiFi Library –WiFiMulti.run

Home / References / ESP32 Library / WiFi API / WiFiMulti

Description

The WiFiMulti.run method is used to manage the connection to multiple WiFi networks configured using the WiFiMulti.addAP method. It attempts to connect to each network in the order they were added, providing a fallback mechanism if the primary network is unavailable. This method is essential for ensuring reliable connectivity in IoT applications.

Syntax and Usage

The WiFiMulti.run method can be used as follows:

uint8_t run(uint32_t connectTimeout = 5000);

Attempts to connect to one of the added APs within the specified timeout period.

Arguments

  • connectTimeout: The maximum time (in milliseconds) to attempt a connection to an AP. This parameter is optional and defaults to 5000 milliseconds (5 seconds).

Return Value

The run() method returns a status code of the connection status. This following list describes the various status codes that indicate the current state of the WiFi connection. Understanding these statuses can help in debugging connection issues and ensuring smooth operation of your IoT projects.

  • WL_IDLE_STATUS (0): The WiFi radio is in an idle state, not attempting to connect.
  • WL_NO_SSID_AVAIL (1): The configured SSID is not available or cannot be found.
  • WL_SCAN_COMPLETED (2): A WiFi network scan has been completed successfully.
  • WL_CONNECTED (3): Successfully connected to the configured WiFi network.
  • WL_CONNECT_FAILED (4): Failed to connect to the configured WiFi network, possibly due to incorrect credentials or other issues.
  • WL_CONNECTION_LOST (5): The connection to the WiFi network was lost, indicating a problem maintaining the connection.
  • WL_DISCONNECTED (6): The WiFi module is disconnected from any WiFi network.

Example Codes

Below are examples demonstrating how to use the WiFiMulti.run method:

Example 1: Basic Usage

This code demonstrates how to use the ESP32 WiFiMulti class’s run() method to connect to the strongest available WiFi network from a list of predefined access points (APs). The run() method continuously checks for available networks and establishes a connection to the best one, ensuring reliable WiFi connectivity in environments with multiple networks.

To use this code, replace “SSID1”, “password1”, and other placeholders with your actual WiFi credentials. Upload the code to your ESP32 and open the Serial Monitor at 115200 baud. The code adds multiple networks using addAP() and uses run() to connect to the best available network. Once connected, it prints the IP address. Ensure the ESP32 is within range of at least one of the specified networks for a successful connection.

/*
 * Author: Avant Maker
 * Date: February 18, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use WiFiMulti.addAP method to add multiple APs and 
 * use WiFiMulti.run to connect to the available AP WiFi.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers,learners, and enthusiasts with the resources
 *  they need to bring their innovative ideas to life.
 */
 
#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti wifiMulti;

void setup() {
    Serial.begin(115200);

    // Add multiple APs
    wifiMulti.addAP("SSID1", "password1");
    wifiMulti.addAP("SSID2", "password2");
    wifiMulti.addAP("SSID3"); // Open network

    // Attempt to connect to the available AP
    if (wifiMulti.run() == WL_CONNECTED) {
        Serial.println("Connected to WiFi!");
        Serial.print("IP Address: ");
        Serial.println(WiFi.localIP());
        // Perform tasks that require Wi-Fi connection here
    } else {
        Serial.println("WiFi not connected!");
        // Handle reconnection or other tasks here
    }
}

void loop() {

}

Example 2: Custom Connection Timeout

This code demonstrates how to use the ESP32 WiFiMulti class’s run() method with a custom timeout to connect to the strongest available WiFi network from a list of predefined access points (APs). The run() method attempts to establish a connection within the specified timeout period, ensuring flexibility in scenarios where quick connectivity is required.

To use this code, replace “SSID1”, “password1”, and other placeholders with your actual WiFi credentials. Upload the code to your ESP32 and open the Serial Monitor at 115200 baud. The code adds multiple networks using addAP() and tries to connect within a 10-second timeout using run(10000). If successful, it prints the IP address; otherwise, it notifies of the failure. Ensure the ESP32 is within range of at least one network for a successful connection.

/*
 * Author: Avant Maker
 * Date: February 18, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use WiFiMulti.addAP method to add multiple APs and 
 * use WiFiMulti.run to specify a custom connection timeout 
 * when attempting to connect to an AP.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers,learners, and enthusiasts with the resources
 *  they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti wifiMulti;

void setup() {
    Serial.begin(115200);

    // Add APs
    wifiMulti.addAP("SSID1", "password1");
    wifiMulti.addAP("SSID2", "password2");

    Serial.println("Connecting...");
    // Attempt to connect with a custom timeout of 10 seconds (10000 milliseconds)
    if (wifiMulti.run(10000) == WL_CONNECTED) {
        Serial.println("Connected to WiFi!");
        Serial.print("IP Address: ");
        Serial.println(WiFi.localIP());
        // Perform tasks that require Wi-Fi connection here
    } else {
        Serial.println("Failed to connect within the timeout period.");
        // Implement fallback or retry logic here
    }
}

void loop() {

}

Example 3: WiFi Reconnect

This code demonstrates how to use the ESP32 WiFiMulti class’s run() method to connect to the strongest available WiFi network from a list of predefined access points (APs). The run() method checks all added networks and establishes a connection to the best available one. Additionally, the loop function includes a mechanism to monitor the WiFi connection status and attempt reconnection if the connection is lost, ensuring reliable and continuous WiFi connectivity.

To use this code, replace “ssid_from_AP_1”, “your_password_for_AP_1”, and other placeholders with your actual WiFi credentials. Upload the code to your ESP32 and open the Serial Monitor at 115200 baud. The code adds multiple networks using addAP() and connects to the best available network using run(). In the loop function, it continuously monitors the WiFi connection status. If the connection drops, it prints “WiFi not connected!” and attempts to reconnect by calling wifiMulti.run(). Ensure the ESP32 is within range of at least one network for a successful initial and subsequent reconnections

/*
 * Author: Avant Maker
 * Date: February 18, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use WiFiMulti.addAP method to add multiple APs and 
 * use WiFiMulti.run method to reconnect to the available 
 * AP WiFi once ESP32 got disconnected.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers,learners, and enthusiasts with the resources
 *  they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti wifiMulti;

void setup() {
  Serial.begin(115200);
  delay(10);

  wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

  Serial.println("Connecting Wifi...");
  if (wifiMulti.run() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("WiFi connected!");
  } else {
    Serial.println("WiFi not connected!");
    Serial.println("Connecting WiFi with wifiMulti.run()");
    wifiMulti.run();
  }
}

AvantMaker Tutorial Suggestion

If you want to learn more about the ESP32’s WiFi capabilities, we’ve created a beginner-friendly guide that explains them in detail. Just click the link below, and you’ll be teleported to that page. It will clear up any confusion you may have while connecting your ESP32 to WiFi or setting it up as a WiFi access point (AP).

ESP32 Essential Guide – Network Section – WiFi Chapter

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!

error: Content is protected !!