ESP32. How to use the WiFiManager library to manage WiFi connections

esp32 wifimanager library test
Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

The WiFiManager library allows you to easily manage the Wi-Fi connection in your ESP32 projects. The WiFiManager library for ESP32 is under development. It starts the ESP32 in access point mode (AP mode) on which you just have to connect to configure the parameters of the WiFi network to which you want to connect.

 

It is also possible to enter other parameters (MQTT server, Token Blynk …) at the same time as the WiFi parameters.

The library also works on ESP8266

Install the WiFiManager library on the Arduino IDE

The ESP32 version of WiFiManager library is not yet available from the library manager of the Arduino IDE.

The ESP32 version is still under development. It must therefore be installed manually.

1 To do this, go directly to the project’s GitHub page and choose the Development version.

Version de développement de la librairie WiFiManager pour ESP32

2 Download the source code of the project without decompressing the ZIP archive.

Télécharger la librairie WiFimanager pour ESP32 à installer sur l'IDE Arduino

3 Open the library manager of the Arduino IDE: Sketches -> Include library -> Add .ZIP library…

Ajouter librairie ZIP depuis l'IDE Arduino

It’s ready.

Add WiFiManager development to a PlatformIO project

For those who use PlatformIO for their projects, it’s even easier to install the library, just add this line to the dependencies

lib_deps =
    https://github.com/tzapu/WiFiManager.git#development

The library will be automatically downloaded on the next build (compilation of the source code).

How the WiFiManager library works

It can also be very interesting not to embed a Wi-Fi network identifier and password in the Arduino code.

For example, the object will have to connect to a network whose credentials you do not know during development. The identifiers may change. For example, in a school or a business, usernames and passwords are changed regularly for security. The access point has been replaced and the new password is different.

In short, you have understood it, by avoiding “hard” coding, you will not need to go through the Arduino IDE each time you change your password or hardware.

This is how the default AutoConnect() mode works

1 When the ESP starts up, it puts it in Station mode and tries to connect to an access point (to the local WiFi network) previously registered
2 If the ESP32 fails to connect or if no network has been registered previously, it places the ESP32 in Access Point mode (AP Mode). A web server accessible to the IP address 192.168.4.1 is started on the ESP32
3 Use any device with a WiFi connection with a browser (computer, smartphone, tablet) to connect to the configuration page

connexion esp32 ap wifimanager

4 If the configuration interface is protected by a password, you must first enter the password

accepter connexion esp32 wifimanager

5 A window titled “Join ….” appears

esp32 ap wifimanager interface

6 Click on Configure WiFi. If the WiFi network to which you want to connect the ESP32 is not displayed, click Refresh and wait a few seconds for the list to refresh.

esp32 wifimanager configure local wifi access point credential
7 Select the WiFi network and enter the password. Click on Save to save.

8 The ESP32 will restart and connect to the configured WiFi network. If all went well, the assigned IP address is displayed in the execution log

ESP32 wifimanager connected local wifi access point

The operation of the autoConnect() method is blocking, that is to say that until the connection parameters are saved, all other processing is pending.

There are several solutions to avoid this behavior, for example

  • AutoConnectWithFSParameters pre-configure connection parameters in a file
  • OnDemandConfigPortal Call up the control panel only when a button or a touch key is pressed
  • AutoConnectWithTimeout we specify a time beyond which we continue the execution of the program (timeout). By testing the connection status, we can put the ESP32 on standby if the WiFi network is not accessible rather than draining the battery

The different connection modes offered by the library

Several methods

  • AutoConnect We let the library try to connect to the WiFi network. This is the easiest method. Two possibilities
    • AutoConnect() the name of the access point is assigned automatically by the library and takes the form ESP_IDENTIFIANTCHIP
    • AutoConnect(“acces_point_name”, “password”) It is possible to customize the name of the access point and optionally protect access with a password.
  • startConfigPortal calls the connection window using a condition (button, touch key …).

Examples installed with the library

Several connection examples are available

exemples librairie wifimanager esp32

Connection methodUsageExample
AutoConnectDefault methodRead
AutoConnectWithStaticIPConfiguration with assignment of a static IP to the ESP32Read
AutoConnectWithFSParametersThe settings are reloaded on startup from a file stored on the SPIFFS file system of the ESP32.Read
AutoConnectWithFSParametersAndCustomIPDitto but with a fixed IP and connection parameters to an MQTT server. The parameters are stored in JSON format using the ArduinoJson libraryRead
AutoConnectWithFeedbackRead
AutoConnectWithFeedbackLEDRead
AutoConnectWithResetRead
AutoConnectWithTimeoutThe autoConnect () method is blocking. To avoid this, it is possible to specify a time beyond which the program execution continues (timeout). By testing the connection status, we can put the ESP32 on standby if the WiFi network is not accessible rather than draining the battery.

if ( WiFi.status() != WL_CONNECTED ) {
   // Activate deep-sleep...
}
Read
OnDemandConfigPortalUsed to invoke AP mode to configure a new connection using a physical control button connected to a pin of the ESP32Read

Upload the WiFiManager project for ESP32

Here is an example to test the Create a new sketch library on the Arduino IDE or a new PlatformIO project and paste the following code.

The program calls the autoConnect() method by default to allow the user to choose the WiFi network to which he wishes to connect.

A button connected to the GPIO of the ESP32 allows you to reset the WiFi parameters.

#include <Arduino.h>
#include <WebServer.h>
#include <WiFiManager.h>         

WebServer server(80);
WiFiManager wm;

#define PIN_RESET_BUTTON 4        
int RESET = 0; 

void handle_root();

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);

    pinMode(PIN_RESET_BUTTON, INPUT);
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    
    //reset saved settings
    //wm.resetSettings();
    
    //Assign fixed IP
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //Try to connect WiFi, then create AP
    wm.autoConnect("ESP32_AP", "esp32_pwd");
    //Idem avec nom automatique de la forme ESP + ChipID et sans mot de passe
    //wifiManager.autoConnect();

    //the library is blocking. Once connected, the program continues
    Serial.println("ESP32 is connected to Wi-Fi network");
    
    // Display an HTML interface to the project from a browser on esp32_ip_address /
    server.on("/", handle_root);

    server.begin();
    Serial.println("HTTP server started");
    delay(100); 
}


void loop() {
    server.handleClient();
    
    RESET = digitalRead(PIN_RESET_BUTTON);
    if( RESET == HIGH) {                                 
      Serial.println("Erase settings and restart ...");
      delay(1000);
      wm.resetSettings();  
      ESP.restart();  
    }
}

// HTML & CSS contents which display on web server
String HTML = "<!DOCTYPE html>\
<html>\
  <body>\
    <h1>Welcome</h1>\
    <p>Your first Iot Project made with ESP32</p>\
    <p>&#128522;</p>\
  </body>\
</html>";

// Handle root url (/)
void handle_root() {
  server.send(200, "text/html", HTML);
}

How the code works

In order to be able to control the WiFiManager library at any time, we initialize an object named vm at the start of the code

WiFiManager wm;

We also created an HTTP server which will be used to display a page of parameters or any other information. This is not necessary in most projects

WebServer server(80);

We will add a button on pin 4 (on an ESP32 DevKitC v4 development board) which will allow you to reset the connection parameters

#define PIN_RESET_BUTTON 4        
int RESET = 0; 

esp32 wifimanager reset button

We launch the connection to the WiFi network in the setup(). If the WiFi network is available and the parameters are known, the connection is directly established, otherwise the ESP32 switches to AP mode and waits for the user to connect and enter the parameters. Here, access to the configuration page is protected by a password

wm.autoConnect("ESP32_AP", "esp32_pwd");
Password must be at least 8 characters long

As soon as the ESP32 is connected to the WiFi network, we start the HTPP server and we wait for the clients on the /

server.on("/", handle_root);
server.begin();
Serial.println("HTTP server started");

As soon as a user arrives on the page, the handleroot() method returns the interface page to him

void handle_root() {
  server.send(200, "text/html", HTML);
}

The page is pre-built in the HTML variable

String HTML = "<!DOCTYPE html>\
<html>\
  <body>\
    <h1>Welcome</h1>\
    <p>Your first Iot Project made with ESP32</p>\
    <p>&#128522;</p>\
  </body>\
</html>";

For the server to work, it must be called regularly in the main loop(). Be careful not to put a delay!

server.handleClient();

Open any internet browser to access the HTML interface of your connected object. To do this, simply enter the IP address of the ESP32 in the address bar (URL)

esp32 html web server interface wifimanager

Finally, as soon as you press the button connected to pin 4, you reset the connection parameters and restart the ESP32.

RESET = digitalRead(PIN_RESET_BUTTON);
if( RESET == HIGH) {                                 
      Serial.println("Erase settings and restart ...");
      delay(1000);
      wm.resetSettings();  
      ESP.restart();  
}

Can we combine with other libraries: pubsubclient, ArduinoOTA …?

Yes, the WiFiManager library is designed to be compatible with other libraries. Indeed, it is an abstraction layer at the ESP8266WiFi library. It only intervenes when the ESP8266 is started. However, as there is always a BUT, I have encountered some difficulties in connecting to an MQTT server. This is probably more of a bad implementation on my part than a real problem in the library. If you have more experience feel free to share in the comments.

To manage the connection to an MQTT server (broker) you can use this example available on GitHub. WiFiManager is able to integrate the input of additional connection parameters. On the other hand, it is necessary to manage either the registration and the loading of the parameters at the launch of the ESP8266 using the method setSaveConfigCallback.

It is also possible to upgrade wirelessly to Wi-Fi using the ArduinoOTA library. However, you must save and reload the connection parameters.

After an update, the WiFiManager library tends to forget the previous connection parameters.

Updates

25/09/2020 Publication of the article

Version française

Click to rate this post!
[Total: 0 Average: 0]

Are you having a problem with this topic?

Maybe someone has already found the solution, visit the forum before asking your question
Ask your question

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

Did you like this project ? Don't miss any more projects by subscribing to our weekly newsletter!

We will be happy to hear your thoughts

      Leave a Reply

      DIY Projects