Skip to content

uPesy only delivers currently in France.

Contents Menu Expand Light mode Dark mode Auto light/dark mode

How to connect to a WiFi network with the ESP32

The built-in WiFi.h library will allow us to use the WiFi features of the ESP32 board easily.

The ESP32 has 2 WiFi modes:

  • STATION ( WIFI_STA ) : The Station mode (STA) is used to connect the ESP32 module to a WiFi access point. The ESP32 behaves like a computer that is connected to our router. If the router is connected to the Internet, then the ESP32 can access the Internet. The ESP32 can behave as a client: make requests to other devices connected to the network or as a server: other devices connected to the network will send requests to the ESP32. In both cases, the ESP32 can access the Internet.

  • AP (Access Point) ( WIFI_AP ): In Access Point mode, the ESP32 behaves like a WiFi network (a bit like a router): other devices can connect to it. In this mode, the ESP32 is not connected to any other network and is therefore not connected to the Internet. This mode is more computationally and energy-intensive (the ESP32 board will heat up) since the ESP32 has to simulate a full WiFi router (Soft AP). The latency and the bandwidth will be less efficient than a classic box.

Note

The ESP32 is by default in STATION mode.

For mode selection :

  • In general, we use the STATION mode. We can access the Internet to retrieve information from an API, have a home automation server with sensors …

  • The AP mode is usually used temporarily to enter the credentials of the WiFi network (SSID and password). It can also be used to have a separate network from your home network and not connected to the Internet.

Connecting to a Wi-Fi Access Point

The code to connect to his box is as follows:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Important

You need to change "yourNetworkName" to the name of your WiFi network and "yourNetworkPassword" to your network password.

Terminal output

Connecting
................
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129

Tip

An easy way for having a WiFi acces pint to test the code, is sharing a WiFi connection from your smartphone.

The code functions as follows:

  • We must include the WiFi.h library.

  • Then we enter the name of the network and its password.

  • We put the ESP32 in STATION mode with the function WiFi.mode(WIFI_STA)

  • The ESP32 tries to connect to the Wi-Fi network using the function WiFi.begin(ssid, password)

  • The connection is not instantaneous! It is therefore necessary to regularly check the connection status: as long as the ESP32 is not connected to the network, we will remain blocked inside the while loop. We add a slight delay to avoid constantly checking the status.

  • Once the connection has been established, the local IP address of the ESP32 on this network will be displayed.

If it is an open network (without a password), then the code becomes simpler:

#include <WiFi.h>

const char* ssid = "yourNetworkName";

void setup(){
Serial.begin(115200);
delay(1000);
WiFi.begin(ssid);
Serial.println("\nConnecting");

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

Serial.println("\nConnected to the WiFi network");
Serial.print("Local ESP32 IP: ");
Serial.println(WiFi.localIP());
}

void loop(){}

Note

Storing logins and passwords in clear text in the code is a bad practice. However, doing so simplify tutorials.

Get WiFi network information

You can get information about the network once you are connected to it:

  • WiFi signal strength (RSSI) with the WiFi.RSSI() function

  • The MAC address of the WiFi network with WiFi.BSSIDstr() or WiFi.macAddress()

  • The local IP address of the ESP32 assigned by the DHCP server of the WiFi network with WiFi.localIP()

  • The local IP address of the WiFi network (gateway) with WiFi.gatewayIP() (usually 192.168.0.1)

  • The subnet mask with WiFi.subnetMask() (usually 255.255.255.0)

The code below displays all this information:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void get_network_info(){
    if(WiFi.status() == WL_CONNECTED) {
        Serial.print("[*] Network information for ");
        Serial.println(ssid);

        Serial.println("[+] BSSID : " + WiFi.BSSIDstr());
        Serial.print("[+] Gateway IP : ");
        Serial.println(WiFi.gatewayIP());
        Serial.print("[+] Subnet Mask : ");
        Serial.println(WiFi.subnetMask());
        Serial.println((String)"[+] RSSI : " + WiFi.RSSI() + " dB");
        Serial.print("[+] ESP32 IP : ");
        Serial.println(WiFi.localIP());
    }
}

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

    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    get_network_info();
}

void loop(){}

Terminal output

Connecting
..............
Connected to the WiFi network
[*] Network information for HUAWEI_**
[+] BSSID : F0:43:47:32:1F:4D
[+] Gateway IP : 192.168.43.1
[+] Subnet Mask : 255.255.255.0
[+] RSSI : -25 dB
[+] ESP32 IP : 192.168.43.129

Debug Wi-Fi connection issues

By monitoring connection status

We can know the status of the WiFi connection with the function WiFi.status() . This function returns an integer according to the current status of the connection.

The possible statuses are :

  • WL_IDLE_STATUS : This is the default status before trying to connect to a network.

  • WL_SCAN_COMPLETED : The WiFi network scan is completed.

  • WL_NO_SSID_AVAIL : The ESP32 cannot find the name of the WiFi network. Either the network is too far from the ESP32, or the name (SSID) of the network is incorrect.

  • WL_CONNECT_FAILED : The ESP32 cannot connect to the designated WiFi network.

  • WL_CONNECTION_LOST : The WiFi connection to the network is lost. If this error occurs repeatedly, it may be a power problem with the ESP32.

  • WL_CONNECTED : The ESP32 is connected to the WiFi network.

  • WL_DISCONNECTED : The ESP32 is disconnected from the WiFi network.

Code that displays the status of the WiFi connection

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

String get_wifi_status(int status){
    switch(status){
        case WL_IDLE_STATUS:
        return "WL_IDLE_STATUS";
        case WL_SCAN_COMPLETED:
        return "WL_SCAN_COMPLETED";
        case WL_NO_SSID_AVAIL:
        return "WL_NO_SSID_AVAIL";
        case WL_CONNECT_FAILED:
        return "WL_CONNECT_FAILED";
        case WL_CONNECTION_LOST:
        return "WL_CONNECTION_LOST";
        case WL_CONNECTED:
        return "WL_CONNECTED";
        case WL_DISCONNECTED:
        return "WL_DISCONNECTED";
    }
}

void setup(){
    Serial.begin(115200);
    delay(1000);
    int status = WL_IDLE_STATUS;
    Serial.println("\nConnecting");
    Serial.println(get_wifi_status(status));
    WiFi.begin(ssid, password);
    while(status != WL_CONNECTED){
        delay(500);
        status = WiFi.status();
        Serial.println(get_wifi_status(status));
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Examples of possible scenarios

If the connection is successful:

Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_CONNECTED

Connected to the WiFi network
Local ESP32 IP: 192.168.43.129

If the SSID cannot be found:

Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL

If the wrong password was used:

Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL

By restarting the ESP32

Occasionally, the ESP32 may temporarily fail to connect to the WiFi for unknown or strange reasons. The best solution is to say that after n seconds, if the ESP32 still hasn’t connected to WiFi, we restart the ESP32. Just add a timeout and use the ESP.restart() function to restart the ESP32 from the code.

Here is an example that will restart the ESP32 after 10 seconds if it is still not connected to WiFi.

#include <WiFi.h>

#define CONNECTION_TIMEOUT 10

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");
    int timeout_counter = 0;

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(200);
        timeout_counter++;
        if(timeout_counter >= CONNECTION_TIMEOUT*5){
        ESP.restart();
        }
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

The ESP32 is reset after 10 seconds in case of connection failure from the code with the the``SW_CPU_RESET`` flag during the boot.

Connecting
.......................................................

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac

Connecting
.......
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129

Advance WiFi network stuffs for the ESP32

Assign a static IP address

The local IP address of the ESP32 has been assigned automatically by the router’s DHCP server. It is convenient to have an IP address automatically on the computer because we do not have to enter it manually. The disadvantage (or advantage, depending on the case) is that the IP address is dynamic: it can change. This can become annoying if, for example, as soon as the ESP32 is restarted (or the DHCP lease is expired), the IP address changes while a web server is running on the ESP32. We would have to find the IP of the ESP32 every time. We can overcome this problem by setting the IP address of the ESP32 on the network. To do this, use the WiFi.config(ip, dns, gateway, subnet) function.

The parameters to be filled in are :

  • IP : The IP address you wish to assign.

  • DNS : Service that links a URL to an IP. By default, we use the DNS server of the router: so we indicate the same address as the router (in general, 192.168.0.1).

  • GATEWAY : This is the IP address of the router (usually 192.168.0.1)

  • SUBNET : Subnet mask (usually 255.255.255.0)

Note

You need to know the router’s IP address: the easiest way is to use the code that displays the WiFi network information in the serial monitor.

In this example, using the WiFi connection sharing of a phone, the router IP address is 192.168.43.1. I choose to have the following static IP 192.168.43.42 for the ESP32.

Code to set the IP address of the ESP32

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

IPAddress ip(192, 168, 43, 42);
IPAddress dns(192, 168, 43, 1);
IPAddress gateway(192, 168, 43, 1);
IPAddress subnet(255, 255, 255, 0);

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

WiFi.config(ip, gateway, subnet, dns);
WiFi.begin(ssid, password);
Serial.println("\nConnecting");

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

Serial.println("\nConnected to the WiFi network");
Serial.print("[+] ESP32 IP : ");
Serial.println(WiFi.localIP());
}

void loop(){}

Warning

It is important to remember not to use an IP address already taken by another device on the network. You can also assign a fixed IP address linked to the MAC address directly from the router settings.

For information purposes, we can then ping the computer to the IP 192.168.43.42 to see if the new address has been taken into account:

Result of a ping in the Windows command prompt

Ping the ESP32 from the Windows terminal (cmd.exe)

Note

Suppose you have the error, ping: transmission failure. General failure , there is probably a software or firewall that disables the use of pings. This can be the case with VPN clients.

Change the MAC address

In some applications, it can be interesting to change the MAC address of the ESP32. We can change the MAC address with a few lines of code using the esp_wifi_set_mac() function.

Note

The MAC address change is temporary and does not replace the original one. You have to upload a new program to find the original MAC address.

#include <WiFi.h>
#include <esp_wifi.h>

uint8_t new_mac[] = {0x60, 0x8B, 0x0E, 0x01, 0x5A, 0x32};

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

    WiFi.mode(WIFI_STA);//Needed to change MAC adress
    Serial.print("[+] Current MAC Address:  ");
    Serial.println(WiFi.macAddress());

    esp_wifi_set_mac(ESP_IF_WIFI_STA, new_mac);

    Serial.print("[+] New MAC Address:  ");
    Serial.println(WiFi.macAddress());
}

void loop(){}

Serial terminal :

[+] Current MAC Address:  24:6F:28:BB:2E:E8
[+] New MAC Address:  60:8B:0E:01:5A:32

Code that connects to a Wi-Fi network with a modified MAC address

#include <WiFi.h>
#include <esp_wifi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

uint8_t new_mac[] = {0x6C, 0x8D, 0xC1, 0x01, 0x5A, 0x32};

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

    WiFi.mode(WIFI_STA);//Needed to change MAC adress
    esp_wifi_set_mac(ESP_IF_WIFI_STA, new_mac);
    delay(1000);
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

A Wireshark capture shows that the address has been changed (here by an Apple MAC address):

wireshark capture changing mac adress esp32

Capture a network frame with Wireshark

Save energy

If you are using an ESP32 in a project that must necessarily use WiFi to work, it is a good idea to set the ESP32 to Deep Sleep mode in case of connection failure to minimize power consumption. This is similar to the ESP32 code that sleeps for 10 seconds between each attempt.

Code that allows putting the ESP32 in Deep Sleep between 2 attempts

#include <WiFi.h>
#include <esp_wifi.h>

//Time in seconds
#define CONNECTION_TIMEOUT 5
#define DEEP_SLEEP_DURATION 10

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup(){
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");
    int timeout_counter = 0;

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
        timeout_counter++;
            if(timeout_counter >= CONNECTION_TIMEOUT*10){
                Serial.println("\nCan't establish WiFi connexion");
                //Setup timer
                esp_sleep_enable_timer_wakeup(DEEP_SLEEP_DURATION * 1000000);
                //Start deep sleep
                esp_deep_sleep_start();
            }
    }
    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Use WiFi events to have an optimized code

Until now, we used to poll the WiFi functions: the ESP32 remains blocked until it receives an event from the ESP32 WiFi driver. We were doing sequential programming. Here’s an example:

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

We regularly check if the ESP32 has successfully connected to the WiFi network. While waiting, we’re not doing anything (we could make calculations between 2 polls) and are stuck in the loop.

A more efficient way of doing this is to use event-driven programming. Indeed, events are generated when the WiFi changes state. The advantage is that we can execute code automatically depending on the event received. This is very similar to the interrupts that we use on the GPIO pins. A change of state of the pin generates an interrupt, which will execute a portion of high-priority code. Here a change of state of the WiFi generates an event that will also execute a portion of code.

The basic code for managing events is as follows:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void my_function(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info){
    //Code
}

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.onEvent(my_function, WIFI_EVENT_ID);

    WiFi.begin(ssid, password);
}

void loop(){}

We use the function WiFi.onEvent(my_function, WIFI_EVENT_ID) to specify which function will be executed when the event WIFI_EVENT_ID is detected. WIFI_EVENT_ID must be replaced by the name or number of the event (see table below). The function my_function() must have the parameters WiFiEvent_t wifi_event , WiFiEventInfo_t wifi_info even if they are not used.

The following code does the same thing as the code at the very beginning to connect to a router, but this time with the use of events when connected to a network.

Code that allows connecting to a router with WiFi events

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void connected_to_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info){
    Serial.println("\nConnected to the WiFi network");
}

void got_ip_from_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info){
    Serial.print("Local ESP32 IP: ");
Serial.println(WiFi.localIP());
}

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.onEvent(connected_to_ap, SYSTEM_EVENT_STA_CONNECTED);
    WiFi.onEvent(got_ip_from_ap, SYSTEM_EVENT_STA_GOT_IP);

    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");
}

void loop(){}

Console output:

Connecting
.............
Connected to the WiFi network
Local ESP32 IP: 192.168.43.167

We use cookies to make your visit to the site as pleasant as possible. Privacy Policy