Table of Contents

The WiFiManager library simplifies the process of connecting an ESP32 to Wi-Fi networks by creating a captive portal for the user to input the Wi-Fi credentials. This is especially useful when you don’t want to hardcode the Wi-Fi details into your sketch.

Installation

  1. Open the Arduino IDE.
  2. Go to SketchInclude LibraryManage Libraries.
  3. In the Library Manager, search for WiFiManager by tzapu.
  4. Click Install to add it to your libraries.

Basic Example

Here’s how to use the WiFiManager library in your project:

#include <WiFiManager.h>

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

  // Create an instance of WiFiManager
  WiFiManager wifiManager;

  // Try to connect to Wi-Fi
  if (!wifiManager.autoConnect("LonelyBinaryAP","12345678")) {
    Serial.println("Failed to connect to Wi-Fi. Rebooting...");
    delay(3000);
    ESP.restart();
  }

  // If connected to Wi-Fi, print the IP
  Serial.println("Connected to Wi-Fi!");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Add your loop code here
}

Before uploading the code, go to Tools and enable the “Erase all flash before sketch upload” option. This will erase the saved Wi-Fi details from the flash. After running the station mode, the SSID and password are saved in the flash memory. WiFiManager will attempt to connect using the saved Wi-Fi credentials. If the connection is successful, you will not see the captive portal created by WiFiManager.

How It Works

WiFiManager wifiManager;
We create an instance of WiFiManager inside the setup() function, which means the instance will be destroyed once the setup() finishes. This ensures that WiFiManager does not consume any additional memory on the ESP32 after the setup is complete. 
wifiManager.autoConnect("LonelyBinaryAP","12345678")

This function will first attempt to connect to the saved Wi-Fi credentials in ESP32’s Flash. If it can’t connect, it will start an access point (AP) with the name you provide (LonelyBinaryAP in this example).

When the ESP32 is in AP mode, the user can open a browser and configure Wi-Fi credentials. Once the credentials are entered, they are stored in the flash memory, so the device can reconnect automatically on future boots.

if (!wifiManager.autoConnect("LonelyBinaryAP","12345678")) {
    Serial.println("Failed to connect to Wi-Fi. Rebooting...");
    delay(3000);
    ESP.restart();
  }

The function wifiManager.autoConnect() returns false when it fails to connect to a Wi-Fi network due to invalid or incorrect credentials, no available Wi-Fi network, or a network timeout. In this case, the ESP32 will restart.

  Serial.println("Connected to Wi-Fi!");
  Serial.println(WiFi.localIP());

After the Wi-Fi is connected, the assigned IP address is printed. Once the setup() function ends, the WiFiManager instance will be deleted from memory, as it was initialized inside the setup() function.

Categorized in:

WiFi,

Tagged in: