Introduction: ESP8266 and ESP32 With WiFiManager

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects.

Are you familiar with WiFiManager? It’s a library that serves as a wireless connection manager, and with it, we have an easier way to configure both an Access Point and a Station. I have received several suggestions to discuss this subject; so today I will introduce you to this library and its functions. I will also make a demonstration of its use with both ESP32 and ESP8266.

Step 1: PINOUT

Here I show the PINOUT of the two devices that we will use:

  • NodeMCU ESP-12E
  • NodeMCU ESP-WROOM-32

Step 2: WiFiManager

The WiFiManager is really nothing more than a library written on top of WiFi.h for easy management of wireless connections. Remember that with it, we have a greater facility to configure both an Access Point and a Station. For Station mode, we configure through a portal in the browser.

Some features:

• It depends on automatic connectivity

• Initialization of non-automatic configuration portal

• Operates selectively in dual mode

Step 3: How It Works

The ESP will initiate a WiFi configuration portal when connected and will save configuration data to non-volatile memory. Subsequently, the configuration portal will only start again if a button is pressed in the ESP module.

Here you can check the configuration flow and follow this step by step:

1. Using any WiFi-enabled device with a browser, connect to the newly created access point and enter the address 192.168.4.1.

2. On the screen you will have two options to connect to an existing network:

• Configure WiFi

• Configure WiFi (No Scan)

3. Choose one of the networks and enter the password (if needed). Then save and wait for the ESP to restart.

4. At the end of the boot, ESP attempts to connect to the saved network. If you can’t do this, you will enable an Access Point.

Step 4: Libraries

Add library "WifiManager-ESP32".

Go to https://github.com/zhouhan0126/WIFIMANAGER-ESP32 and download the library.

Unzip the file and paste it into the libraries folder of the Arduino IDE.

C: / Program Files (x86) / Arduino / libraries

Add "DNSServer-ESP32" library.

Go to the https://github.com/zhouhan0126/DNSServer---esp32 link and download the library.

Unzip the file and paste it into the libraries folder of the Arduino IDE.

C: / Program Files (x86) / Arduino / libraries

Add "WebServer-ESP32" library.

Go to the https://github.com/zhouhan0126/WebServer-esp32 link and download the library.

Unzip the file and paste it into the libraries folder of the Arduino IDE.

C: / Program Files (x86) / Arduino / libraries

Note:

The WiFiManager-ESP32 library already has the settings that work with ESP8266, so we'll only use this, instead of two WiFiManager libs (one for each type of chip).

As we will see later, ESP8266WiFi and ESP8266WebServer are libraries that we don’t need to download, because they already come when we install ESP8266 in the Arduino IDE.

Step 5: Functions

Here are some functions that the WiFiManager offers us.

1. autoConnect

The autoConnect function is responsible for creating an Access Point. We can use it in three ways.

• autoConnect ("network name", "password"); - creates a network with the defined name and password.

• autoConnect ("network name"); - creates an open network with the defined name.

• autoConnect (); - creates an open and automatically named network with the name being 'ESP' + chipID.

2. startConfigPortal

The startConfigPortal function is responsible for creating an Access Point without attempting to connect to a previously saved network.

• startConfigPortal ("network name", "password"); - creates a network with the defined name and password.

• startConfigPortal (); - creates an open and automatically named network with the name being 'ESP' + chipID.

3. getConfigPortalSSID

Returns the SSID of the portal (Access Point)

4. getSSID

This returns the SSID of the network to which it is connected.

5. getPassword

This returns the password of the network to which it is connected.

6. setDebugOutput

The setDebugOutput function is responsible for printing debug messages on the serial monitor. These messages are already defined in the library. As you go through the functions, the data will be printed.

By default, this function is set to TRUE. If you want to disable the messages, simply set the function to FALSE.

7. setMinimumSignalQuality

The setMinimumSignalQuality function is responsible for filtering networks based on signal quality. By default, WiFiManager will not show sign-on networks below 8%.

8. setRemoveDuplicateAPs

The setRemoveDuplicateAPs function is responsible for removing network duplicates.

By default it is set to TRUE.

9. setAPStaticIPConfig

The setAPStaticIPConfig function is responsible for setting the static address settings when in access point mode.

(IP, GATEWAY, SUBNET)

10. setSTAStaticIPConfig

The setSTAStaticIPConfig function is responsible for setting the static address settings when in station mode.

(IP, GATEWAY, SUBNET)

You must add the command before autoConnect!!!

11. setAPCallback

The setAPCallback function is responsible for informing you that AP mode has started.

The parameter is a function that must be created to indicate it as a callback;

12. setSaveConfigCallback

The setSaveConfigCallback function is responsible for informing you that a new configuration has been saved and the connection has been successfully completed.

The parameter is a function to create and indicates this as an allback.

You must add the command before autoConnect !!!

Step 6: Assembly

Example

In our example, we will create an Access Point with ESP (the code will serve both ESP8266 and ESP32). After the creation of the AP, we will access the portal through IP 192.168.4.1 (which is the default to access it). So let's get the available networks, select one and save. From there, the ESP will restart and attempt to connect to it, and then it will work as a station and no longer as an Access Point.

After entering station mode, you can make the ESP return to Access Point mode only through the button.

Step 7: Code

Libraries

First let's define the libraries that we will use.

Note that we have #if defined, #else, and #endif commands. They are conditional to include necessary libraries pertaining to the chip. This part is extremely important to run the same code on both ESP8266 and ESP32.

#if defined(ESP8266)
#include <ESP8266WiFi.h>  //ESP8266 Core WiFi Library         
#else
#include <WiFi.h>      //ESP32 Core WiFi Library    
#endif


#if defined(ESP8266)

#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal

#else

#include <WebServer.h> //Local DNS Server used for redirecting all requests to the configuration portal ( https://github.com/zhouhan0126/DNSServer---esp32 )

#endif

#include <DNSServer.h> //Local WebServer used to serve the configuration portal ( https://github.com/zhouhan0126/DNSServer---esp32 ) #include <WiFiManager.h> // WiFi Configuration Magic ( https://github.com/zhouhan0126/DNSServer---esp32 ) >> https://github.com/zhouhan0126/DNSServer---esp32 (ORIGINAL)

Step 8: Setup

In setup, we are configuring our WiFiManager in the simplest way. Let's just define the callbacks and create the network.

const int PIN_AP = 2;
void setup() {
  Serial.begin(9600);
  pinMode(PIN_AP, INPUT);
  //declaração do objeto wifiManager
  WiFiManager wifiManager;

//utilizando esse comando, as configurações são apagadas da memória
//caso tiver salvo alguma rede para conectar automaticamente, ela é apagada. // wifiManager.resetSettings(); //callback para quando entra em modo de configuração AP wifiManager.setAPCallback(configModeCallback); //callback para quando se conecta em uma rede, ou seja, quando passa a trabalhar em modo estação wifiManager.setSaveConfigCallback(saveConfigCallback); //cria uma rede de nome ESP_AP com senha 12345678 wifiManager.autoConnect("ESP_AP", "12345678"); }

Step 9: Loop

In the loop, we will read the button pin to see if it has been pressed, and then we will call the method to re-enable the AP mode.

void loop() {

  WiFiManager wifiManager;
  //se o botão foi pressionado
   if ( digitalRead(PIN_AP) == HIGH ) {
      Serial.println("resetar"); //tenta abrir o portal
      if(!wifiManager.startConfigPortal("ESP_AP", "12345678") ){
        Serial.println("Falha ao conectar");
        delay(2000);
        ESP.restart();
        delay(1000);
      }
      Serial.println("Conectou ESP_AP!!!");
   }

When you press the button, ESP will exit Station mode and open your Access Point and portal.

Remember that we do not use the resetSettings () command. The settings are still saved for the next time the ESP boots.

Step 10: Callbacks

The callback functions, which are associated with events, serve for you to have the exact moment of an operation, in our case, entering AP mode and Station mode. We can then implement some desired routine, such as retrieving the SSID from the connected network, for example.

//callback que indica que o ESP entrou no modo AP
void configModeCallback (WiFiManager *myWiFiManager) {  
//  Serial.println("Entered config mode");
  Serial.println("Entrou no modo de configuração");
  Serial.println(WiFi.softAPIP()); //imprime o IP do AP
  Serial.println(myWiFiManager->getConfigPortalSSID()); //imprime o SSID criado da rede</p><p>}</p><p>//callback que indica que salvamos uma nova rede para se conectar (modo estação)
void saveConfigCallback () {
//  Serial.println("Should save config");
  Serial.println("Configuração salva");
  Serial.println(WiFi.softAPIP()); //imprime o IP do AP
}