ESP32 Useful Wi-Fi Library Functions (Arduino IDE)

This article is a compilation of useful Wi-Fi functions for the ESP32. We’ll cover the following topics: scan Wi-Fi networks, connect to a Wi-Fi network, get Wi-Fi connection strength, check connection status, reconnect to the network after a connection is lost, Wi-Fi status, Wi-Fi modes, get the ESP32 IP address, set a fixed IP address and more.

This is not a novelty. There are plenty of examples of how to handle Wi-Fi with the ESP32. However, we thought it would be useful to compile some of the most used and practical Wi-Fi functions for the ESP32.

ESP32 Useful Wi-Fi Library Functions Arduino IDE

Table of Contents

Here’s a list of what will be covered in this tutorial (you can click on the links to go to the corresponding section):

Including the Wi-Fi Library

The first thing you need to do to use the ESP32 Wi-Fi functionalities is to include the WiFi.h library in your code, as follows:

#include <WiFi.h>

This library is automatically “installed” when you install the ESP32 add-on in your Arduino IDE. If you don’t have the ESP32 installed, you can follow the next tutorial:

If you prefer to use VS Code + PaltformIO, you just need to start a new project with an ESP32 board to be able to use the WiFi.h library and its functions.

ESP32 Wi-Fi Modes

The ESP32 board can act as Wi-Fi Station, Access Point or both. To set the Wi-Fi mode, use WiFi.mode() and set the desired mode as argument:

WiFi.mode(WIFI_STA)station mode: the ESP32 connects to an access point
WiFi.mode(WIFI_AP)access point mode: stations can connect to the ESP32
WiFi.mode(WIFI_AP_STA)access point and a station connected to another access point

Wi-Fi Station

When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). In this scenario, the router assigns a unique IP address to your ESP board. You can communicate with the ESP using other devices (stations) that are also connected to the same network by referring to the ESP unique IP address.

ESP32 Station Mode Router access point

The router is connected to the internet, so we can request information from the internet using the ESP32 board like data from APIs (weather data, for example), publish data to online platforms, use icons and images from the internet or include JavaScript libraries to build web server pages.

Set the ESP32 as a Station and Connect to Wi-Fi Network

Go to “Connect to Wi-Fi Network” to learn how to set the ESP32 as station and connect it to a network.

In some cases, this might not be the best configuration – when you don’t have a network nearby and want you still want to connect to the ESP to control it. In this scenario, you must set your ESP board as an access point.

Access Point

When you set your ESP32 board as an access point, you can be connected using any device with Wi-Fi capabilities without connecting to your router. When you set the ESP32 as an access point, you create its own Wi-Fi network, and nearby Wi-Fi devices (stations) can connect to it, like your smartphone or computer. So, you don’t need to be connected to a router to control it.

This can be also useful if you want to have several ESP32 devices talking to each other without the need for a router.

ESP32 Access Point Mode

Because the ESP32 doesn’t connect further to a wired network like your router, it is called soft-AP (soft Access Point). This means that if you try to load libraries or use firmware from the internet, it will not work. It also doesn’t work if you make HTTP requests to services on the internet to publish sensor readings to the cloud or use services on the internet (like sending an email, for example).

Set the ESP32 as an Access Point

To set the ESP32 as an access point, set the Wi-Fi mode to access point:

WiFi.mode(WIFI_AP)

And then, use the softAP() method as follows:

WiFi.softAP(ssid, password);

ssid is the name you want to give to the ESP32 access point, and the password variable is the password for the access point. If you don’t want to set a password, set it to NULL.

There are also other optional parameters you can pass to the softAP() method. Here are all the parameters:

WiFi.softAP(const char* ssid, const char* password, int channel, int ssid_hidden, int max_connection)
  • ssid: name for the access point – maximum of 63 characters;
  • password: minimum of 8 characters; set to NULL if you want the access point to be open;
  • channel: Wi-Fi channel number (1-13)
  • ssid_hidden: (0 = broadcast SSID, 1 = hide SSID)
  • max_connection: maximum simultaneous connected clients (1-4)

We have a complete tutorial explaining how to set up the ESP32 as an access point:

Wi-Fi Station + Access Point

The ESP32 can be set as a Wi-Fi station and access point simultaneously. Set its mode to WIFI_AP_STA.

WiFi.mode(WIFI_AP_STA);

Scan Wi-Fi Networks

The ESP32 can scan nearby Wi-Fi networks within its Wi-Fi range. In your Arduino IDE, go to File > Examples > WiFi > WiFiScan. This will load a sketch that scans Wi-Fi networks within the range of your ESP32 board.

ESP32 Scan WiFi Networks

This can be useful to check if the Wi-Fi network you’re trying to connect is within the range of your board or other applications. Your Wi-Fi project may not often work because it may not be able to connect to your router due to insufficient Wi-Fi strength.

Here’s the example:

/*
  Example from WiFi > WiFiScan
  Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/
*/

#include "WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
      Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

View raw code

You can upload it to your board and check the available networks as well as the RSSI (received signal strength indicator).

WiFi.scanNetworks() returns the number of networks found.

int n = WiFi.scanNetworks();

After the scanning, you can access the parameters about each network.

WiFi.SSID() prints the SSID for a specific network:

Serial.print(WiFi.SSID(i));

WiFi.RSSI() returns the RSSI of that network. RSSI stands for Received Signal Strength Indicator. It is an estimated measure of power level that an RF client device is receiving from an access point or router.

Serial.print(WiFi.RSSI(i));

Finally, WiFi.encryptionType() returns the network encryption type. That specific example puts a * in the case of open networks. However, that function can return one of the following options (not just open networks):

  • WIFI_AUTH_OPEN
  • WIFI_AUTH_WEP
  • WIFI_AUTH_WPA_PSK
  • WIFI_AUTH_WPA2_PSK
  • WIFI_AUTH_WPA_WPA2_PSK
  • WIFI_AUTH_WPA2_ENTERPRISE
ESP32 Scan WiFi Networks Example Serial Monitor

Connect to a Wi-Fi Network

To connect the ESP32 to a specific Wi-Fi network, you must know its SSID and password. Additionally, that network must be within the ESP32 Wi-Fi range (to check that, you can use the previous example to scan Wi-Fi networks).

You can use the following function to connect the ESP32 to a Wi-Fi network initWiFi():

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

The ssid and password variables hold the SSID and password of the network you want to connect to.

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Then, you simply need to call the initWiFi() function in your setup().

How it Works?

Let’s take a quick look on how this function works.

First, set the Wi-Fi mode. If the ESP32 will connected to another network (access point/hotspot) it must be in station mode.

WiFi.mode(WIFI_STA);

Then, use WiFi.begin() to connect to a network. You must pass as arguments the network SSID and its password:

WiFi.begin(ssid, password);

Connecting to a Wi-Fi network can take a while, so we usually add a while loop that keeps checking if the connection was already established by using WiFi.status(). When the connection is successfully established, it returns WL_CONNECTED.

while (WiFi.status() != WL_CONNECTED) {

Get Wi-Fi Connection Status

To get the status of the Wi-Fi connection, you can use WiFi.status(). This returns one of the following values that correspond to the constants on the table:

ValueConstantMeaning
0WL_IDLE_STATUStemporary status assigned when WiFi.begin() is called
1WL_NO_SSID_AVAIL when no SSID are available
2WL_SCAN_COMPLETEDscan networks is completed
3WL_CONNECTEDwhen connected to a WiFi network
4WL_CONNECT_FAILEDwhen the connection fails for all the attempts
5WL_CONNECTION_LOSTwhen the connection is lost
6WL_DISCONNECTEDwhen disconnected from a network

Get WiFi Connection Strength

To get the WiFi connection strength, you can simply call WiFi.RSSI() after a WiFi connection.

Here’s an example:

/*
  Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  // put your main code here, to run repeatedly:
}

View raw code

Insert your network credentials and upload the code.

Open the Serial Monitor and press the ESP32 on-board RST button. It will connect to your network and print the RSSI (received signal strength indicator).

Get ESP32 Wi-Fi Connection Strength

A lower absolute value means a strongest Wi-Fi connection.

Get ESP32 IP Address

When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). In this scenario, the router assigns a unique IP address to your ESP32 board. To get your board’s IP address, you need to call WiFi.localIP() after establishing a connection with your network.

Serial.println(WiFi.localIP());

Set a Static ESP32 IP Address

Instead of getting a randomly assigned IP address, you can set an available IP address of your preference to the ESP32 using WiFi.config().

Outside the setup() and loop() functions, define the following variables with your own static IP address and corresponding gateway IP address. By default, the following code assigns the IP address 192.168.1.184 that works in the gateway 192.168.1.1.

// Set your Static IP address
IPAddress local_IP(192, 168, 1, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);

IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);   // optional
IPAddress secondaryDNS(8, 8, 4, 4); // optional

Then, in the setup() you need to call the WiFi.config() method to assign the configurations to your ESP32.

// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
  Serial.println("STA Failed to configure");
}

The primaryDNS and secondaryDNS parameters are optional and you can remove them.

We recommend reading the following tutorial to learn how to set a static IP address:

Disconnect from Wi-Fi Network

To disconnect from a previously connected Wi-Fi network, use WiFi.disconnect():

WiFi.disconnect()
ESP32 Disconnect From Wi-Fi Network

Reconnect to Wi-Fi Network After Lost Connection

To reconnect to Wi-Fi after a connection is lost, you can use WiFi.reconnect() to try to reconnect to the previously connected access point:

WiFi.reconnect()

Or, you can call WiFi.disconnect() followed by WiFi.begin(ssid,password).

WiFi.disconnect();
WiFi.begin(ssid, password);

Alternatively, you can also try to restart the ESP32 with ESP.restart() when the connection is lost.

You can add something like the snippet below to your loop() that checks once in a while if the board is connected.

unsigned long currentMillis = millis();
// if WiFi is down, try reconnecting
if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
  Serial.print(millis());
  Serial.println("Reconnecting to WiFi...");
  WiFi.disconnect();
  WiFi.reconnect();
  previousMillis = currentMillis;
}

Don’t forget to declare the previousMillis and interval variables. The interval corresponds to the period of time between each check in milliseconds (for example 30 seconds):

unsigned long previousMillis = 0;
unsigned long interval = 30000;

Here’s a complete example.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp32-to-wifi/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

unsigned long previousMillis = 0;
unsigned long interval = 30000;

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RSSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
    Serial.print(millis());
    Serial.println("Reconnecting to WiFi...");
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
}

View raw code

This example shows how to connect to a network and checks every 30 seconds if it is still connected. If it isn’t, it disconnects and tries to reconnect again.

You can read our guide: [SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection.

Alternatively, you can also use WiFi Events to detect that the connection was lost and call a function to handle what to do when that happens (see the next section).

ESP32 Wi-Fi Events

The ESP32 can handle all the following Wi-Fi events (check the source code):

0ARDUINO_EVENT_WIFI_READYESP32 Wi-Fi ready
1ARDUINO_EVENT_WIFI_SCAN_DONEESP32 finishes scanning AP
2ARDUINO_EVENT_WIFI_STA_STARTESP32 station start
3ARDUINO_EVENT_WIFI_STA_STOPESP32 station stop
4ARDUINO_EVENT_WIFI_STA_CONNECTEDESP32 station connected to AP
5ARDUINO_EVENT_WIFI_STA_DISCONNECTEDESP32 station disconnected from AP
6ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGEthe auth mode of AP connected by ESP32 station changed
7ARDUINO_EVENT_WIFI_STA_GOT_IPESP32 station got IP from connected AP
8ARDUINO_EVENT_WIFI_STA_LOST_IPESP32 station lost IP and the IP is reset to 0
9ARDUINO_EVENT_WPS_ER_SUCCESSESP32 station wps succeeds in enrollee mode
10ARDUINO_EVENT_WPS_ER_FAILEDESP32 station wps fails in enrollee mode
11ARDUINO_EVENT_WPS_ER_TIMEOUTESP32 station wps timeout in enrollee mode
12ARDUINO_EVENT_WPS_ER_PINESP32 station wps pin code in enrollee mode
13ARDUINO_EVENT_WIFI_AP_STARTESP32 soft-AP start
14ARDUINO_EVENT_WIFI_AP_STOPESP32 soft-AP stop
15ARDUINO_EVENT_WIFI_AP_STACONNECTEDa station connected to ESP32 soft-AP
16ARDUINO_EVENT_WIFI_AP_STADISCONNECTEDa station disconnected from ESP32 soft-AP
17ARDUINO_EVENT_WIFI_AP_STAIPASSIGNEDESP32 soft-AP assign an IP to a connected station
18ARDUINO_EVENT_WIFI_AP_PROBEREQRECVEDReceive probe request packet in soft-AP interface
19ARDUINO_EVENT_WIFI_AP_GOT_IP6ESP32 access point v6IP addr is preferred
19ARDUINO_EVENT_WIFI_STA_GOT_IP6ESP32 station v6IP addr is preferred
19ARDUINO_EVENT_ETH_GOT_IP6Ethernet IPv6 is preferred
20ARDUINO_EVENT_ETH_STARTESP32 ethernet start
21ARDUINO_EVENT_ETH_STOPESP32 ethernet stop
22ARDUINO_EVENT_ETH_CONNECTEDESP32 ethernet phy link up
23ARDUINO_EVENT_ETH_DISCONNECTEDESP32 ethernet phy link down
24ARDUINO_EVENT_ETH_GOT_IPESP32 ethernet got IP from connected AP
25ARDUINO_EVENT_MAX

For a complete example on how to use those events, in your Arduino IDE, go to File > Examples > WiFi > WiFiClientEvents.

/*   This sketch shows the WiFi event usage - Example from WiFi > WiFiClientEvents
     Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/  */
/*
* WiFi Events

0  ARDUINO_EVENT_WIFI_READY               < ESP32 WiFi ready
1  ARDUINO_EVENT_WIFI_SCAN_DONE                < ESP32 finish scanning AP
2  ARDUINO_EVENT_WIFI_STA_START                < ESP32 station start
3  ARDUINO_EVENT_WIFI_STA_STOP                 < ESP32 station stop
4  ARDUINO_EVENT_WIFI_STA_CONNECTED            < ESP32 station connected to AP
5  ARDUINO_EVENT_WIFI_STA_DISCONNECTED         < ESP32 station disconnected from AP
6  ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE      < the auth mode of AP connected by ESP32 station changed
7  ARDUINO_EVENT_WIFI_STA_GOT_IP               < ESP32 station got IP from connected AP
8  ARDUINO_EVENT_WIFI_STA_LOST_IP              < ESP32 station lost IP and the IP is reset to 0
9  ARDUINO_EVENT_WPS_ER_SUCCESS       < ESP32 station wps succeeds in enrollee mode
10 ARDUINO_EVENT_WPS_ER_FAILED        < ESP32 station wps fails in enrollee mode
11 ARDUINO_EVENT_WPS_ER_TIMEOUT       < ESP32 station wps timeout in enrollee mode
12 ARDUINO_EVENT_WPS_ER_PIN           < ESP32 station wps pin code in enrollee mode
13 ARDUINO_EVENT_WIFI_AP_START                 < ESP32 soft-AP start
14 ARDUINO_EVENT_WIFI_AP_STOP                  < ESP32 soft-AP stop
15 ARDUINO_EVENT_WIFI_AP_STACONNECTED          < a station connected to ESP32 soft-AP
16 ARDUINO_EVENT_WIFI_AP_STADISCONNECTED       < a station disconnected from ESP32 soft-AP
17 ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED         < ESP32 soft-AP assign an IP to a connected station
18 ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED        < Receive probe request packet in soft-AP interface
19 ARDUINO_EVENT_WIFI_AP_GOT_IP6               < ESP32 ap interface v6IP addr is preferred
19 ARDUINO_EVENT_WIFI_STA_GOT_IP6              < ESP32 station interface v6IP addr is preferred
20 ARDUINO_EVENT_ETH_START                < ESP32 ethernet start
21 ARDUINO_EVENT_ETH_STOP                 < ESP32 ethernet stop
22 ARDUINO_EVENT_ETH_CONNECTED            < ESP32 ethernet phy link up
23 ARDUINO_EVENT_ETH_DISCONNECTED         < ESP32 ethernet phy link down
24 ARDUINO_EVENT_ETH_GOT_IP               < ESP32 ethernet got IP from connected AP
19 ARDUINO_EVENT_ETH_GOT_IP6              < ESP32 ethernet interface v6IP addr is preferred
25 ARDUINO_EVENT_MAX
*/

#include <WiFi.h>

const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

void WiFiEvent(WiFiEvent_t event){
    Serial.printf("[WiFi-event] event: %d\n", event);

    switch (event) {
        case ARDUINO_EVENT_WIFI_READY: 
            Serial.println("WiFi interface ready");
            break;
        case ARDUINO_EVENT_WIFI_SCAN_DONE:
            Serial.println("Completed scan for access points");
            break;
        case ARDUINO_EVENT_WIFI_STA_START:
            Serial.println("WiFi client started");
            break;
        case ARDUINO_EVENT_WIFI_STA_STOP:
            Serial.println("WiFi clients stopped");
            break;
        case ARDUINO_EVENT_WIFI_STA_CONNECTED:
            Serial.println("Connected to access point");
            break;
        case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
            Serial.println("Disconnected from WiFi access point");
            break;
        case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
            Serial.println("Authentication mode of access point has changed");
            break;
        case ARDUINO_EVENT_WIFI_STA_GOT_IP:
            Serial.print("Obtained IP address: ");
            Serial.println(WiFi.localIP());
            break;
        case ARDUINO_EVENT_WIFI_STA_LOST_IP:
            Serial.println("Lost IP address and IP address is reset to 0");
            break;
        case ARDUINO_EVENT_WPS_ER_SUCCESS:
            Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_FAILED:
            Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_TIMEOUT:
            Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_PIN:
            Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
            break;
        case ARDUINO_EVENT_WIFI_AP_START:
            Serial.println("WiFi access point started");
            break;
        case ARDUINO_EVENT_WIFI_AP_STOP:
            Serial.println("WiFi access point  stopped");
            break;
        case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
            Serial.println("Client connected");
            break;
        case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
            Serial.println("Client disconnected");
            break;
        case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
            Serial.println("Assigned IP address to client");
            break;
        case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
            Serial.println("Received probe request");
            break;
        case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
            Serial.println("AP IPv6 is preferred");
            break;
        case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
            Serial.println("STA IPv6 is preferred");
            break;
        case ARDUINO_EVENT_ETH_GOT_IP6:
            Serial.println("Ethernet IPv6 is preferred");
            break;
        case ARDUINO_EVENT_ETH_START:
            Serial.println("Ethernet started");
            break;
        case ARDUINO_EVENT_ETH_STOP:
            Serial.println("Ethernet stopped");
            break;
        case ARDUINO_EVENT_ETH_CONNECTED:
            Serial.println("Ethernet connected");
            break;
        case ARDUINO_EVENT_ETH_DISCONNECTED:
            Serial.println("Ethernet disconnected");
            break;
        case ARDUINO_EVENT_ETH_GOT_IP:
            Serial.println("Obtained IP address");
            break;
        default: break;
    }}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));
}

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

    // delete old config
    WiFi.disconnect(true);

    delay(1000);

    // Examples of different ways to register wifi events
    WiFi.onEvent(WiFiEvent);
    WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
    WiFiEventId_t eventID = WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
        Serial.print("WiFi lost connection. Reason: ");
        Serial.println(info.wifi_sta_disconnected.reason);
    }, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

    // Remove WiFi event
    Serial.print("WiFi Event ID: ");
    Serial.println(eventID);
    // WiFi.removeEvent(eventID);

    WiFi.begin(ssid, password);

    Serial.println();
    Serial.println();
    Serial.println("Wait for WiFi... ");
}

void loop(){
    delay(1000);
}

View raw code

With Wi-Fi Events, you don’t need to be constantly checking the Wi-Fi state. When a certain event happens, it automatically calls the corresponding handling function.

Reconnect to Wi-Fi Network After Lost Connection (Wi-Fi Events)

Wi-Fi events can be useful to detect that a connection was lost and try to reconnect right after (use the SYSTEM_EVENT_AP_STADISCONNECTED event). Here’s a sample code:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp32-to-wifi/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
 
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.wifi_sta_disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

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

  // delete old config
  WiFi.disconnect(true);

  delay(1000);

  WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

  /* Remove WiFi event
  Serial.print("WiFi Event ID: ");
  Serial.println(eventID);
  WiFi.removeEvent(eventID);*/

  WiFi.begin(ssid, password);
    
  Serial.println();
  Serial.println();
  Serial.println("Wait for WiFi... ");
}

void loop(){
  delay(1000);
}

View raw code

How it Works?

In this example we’ve added three Wi-Fi events: when the ESP32 connects, when it gets an IP address, and when it disconnects: ARDUINO_EVENT_WIFI_STA_CONNECTED, ARDUINO_EVENT_WIFI_STA_GOT_IP, ARDUINO_EVENT_WIFI_STA_DISCONNECTED.

When the ESP32 station connects to the access point (ARDUINO_EVENT_WIFI_STA_CONNECTED event), the WiFiStationConnected() function will be called:

 WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);

The WiFiStationConnected() function simply prints that the ESP32 connected to an access point (for example, your router) successfully. However, you can modify the function to do any other task (like light up an LED to indicate that it is successfully connected to the network).

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

When the ESP32 gets its IP address, the WiFiGotIP() function runs.

 WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);

That function simply prints the IP address on the Serial Monitor.

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

When the ESP32 loses the connection with the access point (ARDUINO_EVENT_WIFI_STA_DISCONNECTED), the WiFiStationDisconnected() function is called.

 WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

That function prints a message indicating that the connection was lost and tries to reconnect:

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.wifi_sta_disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

ESP32 WiFiMulti

The ESP32 WiFiMulti allows you to register multiple networks (SSID/password combinations). The ESP32 will connect to the Wi-Fi network with the strongest signal (RSSI). If the connection is lost, it will connect to the next network on the list. This requires that you include the WiFiMulti.h library (you don’t need to install it, it comes by default with the ESP32 package).

To learn how to use WiFiMulti, read the following tutorial:

Change ESP32 Hostname

To set a custom hostname for your board, call WiFi.setHostname(YOUR_NEW_HOSTNAME); before WiFi.begin();

The default ESP32 hostname is espressif.

There is a method provided by the WiFi.h library that allows you to set a custom hostname.

First, start by defining your new hostname. For example:

String hostname = "ESP32 Node Temperature";

Then, call the WiFi.setHostname() function before calling WiFi.begin(). You also need to call WiFi.config() as shown below:

WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(hostname.c_str()); //define hostname

You can copy the complete example below:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-set-custom-hostname-arduino/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

String hostname = "ESP32 Node Temperature";

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname(hostname.c_str()); //define hostname
  //wifi_station_set_hostname( hostname.c_str() );
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  // put your main code here, to run repeatedly:
}

View raw code

You can use this previous snippet of code in your projects to set a custom hostname for the ESP32.

Important: you may need to restart your router for the changes to take effect.

After this, if you go to your router settings, you’ll see the ESP32 with the custom hostname.

ESP32 Custom Hostname setting Arduino IDE

Wrapping Up

This article was a compilation of some of the most used and useful ESP32 Wi-Fi functions. Although there are plenty of examples of using the ESP32 Wi-Fi capabilities, there is little documentation explaining how to use the Wi-Fi functions with the ESP32 using Arduino IDE. So, we’ve decided to put together this guide to make it easier to use ESP32 Wi-Fi-related functions in your projects.

If you have other suggestions, you can share them in the comments section.

We hope you’ve found this tutorial useful.

Learn more about the ESP32 with our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

90 thoughts on “ESP32 Useful Wi-Fi Library Functions (Arduino IDE)”

  1. Hi
    Your blog is very interresting and helps a lot, but i miss the information to change the hostname of the esp32. Is it possible to change the Espressif unit name to a project specifish name.
    I know i can change the name in the wlan router but the unit name still is Espressif

    Regards

    Reply
  2. Is there a way to quickly do a WiFi Scan for a SPECIFIC SSID and, when it detects the WiFi SSID is available (or not), does something with this information in the sketch?

    Reply
    • Hi Jim,

      Something like that?

      #include <Arduino.h>
      #include <WiFi.h>

      const char* SPECIFIC_SSID = "MyNetwork";
      const char* ENC_TYPE[] = {
      "Open",
      "WEP",
      "WPA_PSK",
      "WPA2_PSK",
      "WPA_WPA2_PSK",
      "WPA2_ENTERPRISE",
      "MAX"
      };

      struct WiFiInfo {
      bool found;
      int32_t channel;
      int32_t rssi;
      wifi_auth_mode_t auth_mode;
      } wifi_info;

      void findWiFi(const char *ssid, WiFiInfo *info) {
      info->found = false;
      int16_t n = WiFi.scanNetworks();
      for (uint8_t i=0; i<n; ++i) {
      if (strcmp(WiFi.SSID(i).c_str(), ssid) == 0) {
      info->found = true;
      info->channel = WiFi.channel(i);
      info->rssi = WiFi.RSSI(i);
      info->auth_mode = WiFi.encryptionType(i);
      return;
      }
      }
      }

      void setup() {
      Serial.begin(115200);
      findWiFi(SPECIFIC_SSID, &wifi_info);
      Serial.printf(wifi_info.found
      ? "SSID: %s, channel: %i, RSSI: %i dBm, encryption: %s\n"
      : "SSID: %s ... could not be found\n",
      SPECIFIC_SSID,
      wifi_info.channel,
      wifi_info.rssi,
      ENC_TYPE[wifi_info.auth_mode]);
      }

      void loop() {}

      Reply
          • Hi.
            No. It needs to be on the same network as the MQTTT broker, or have access to the internet to connect to a cloud broker.
            Regards,
            Sara

      • This worked perfectly. Thank you! I wonder if there is a faster way to get the SSID without having to scan for all networks first, and then isolating the network I’m searching for. Is there a way to do this?

        Reply
      • hi, I hope someone can help me with this issue becasue I have weeks working on it and nothing looks to work….. I have a esp32 with my basic code just to connect with my wifi, not matter what I do, it does not connect, always shows me the error disconnected from AP (event 5)…. do you have any idea what is this happening? thanks

        Reply
  3. To use as a WiFi reference, there is a couple of things I would’ve liked to see included; i.e., commands to manipulate the MAC address of a board, and an example using the soft_AP and STA modes together.

    As Werner noted, if there is a way to redefine the identifier, that would be great to know too!

    That said, it is still a great article, and I would love to see it expanded with more examples of the more obscure commands’ responses. Maybe a downloadable table of the command/method/event, use format, possible responses, and any comments (such as “only valid in STA mode” or, a link to an example. Most of this is already in the article, just not well summarized, so hard to locate.

    Cheers!

    Reply
  4. Great tutorial!
    Thanks for your work.
    I found the automatic reconnection feature after the card disconnected very interesting. However, they seem to understand that this doesn’t always work. Especially when using Blynk. Has anyone had any experience in this regard?
    Greetings. Mike.

    Reply
  5. Is it now possible to run ESP-Now together with WiFi in STA mode?
    My last state was: ESP-Now and WiFi must share the same channel and the channel number must be 1. Even when the router starts a connection at channel 1 in STA mode, if the router changes the channel to avoid traffic collisions, the ESP-Now connection breaks.

    Reply
  6. Great Tutorial!
    I am having some trouble connecting to my local WiFi and I’m sure this info will help me understand what is happening.

    Do you have something similar for the ESP8266?

    Reply
  7. What I would find most useful would be some sample code that:

    attempted a connection with stored network ID and credentials
    if this failed fall back to AP mode, so that a user can connect, login to a webUI, save new network details, and then reboot / attempt to reconnect.

    No-one want to recompile code, just so a device can change networks.

    Reply
  8. It’s a pity that you omitted WiFi.persistent() command. I think, that this function is one of the most important when using WiFi and literally nobody knows about it.

    In short: This function is true on default and causes, that every time (on every reboot) when calling WiFi.begin the ssid+pass are written into flash. This is a flash killer when using WiFi and deepsleep together.

    Reply
  9. Hi,
    Thank you for publishing the article.
    Regarding Reconnect to Wi-Fi Network After Lost Connection code
    I have a need to modify the while loop so it checks for two conditions for example
    (WiFi.status() != WL_CONNECTED) or (WiFi.status() != WL_NO_SSID_AVAIL)

    Could you advice me of the best approach

    Best regards

    Reply
  10. I have found that setting a static IP address in Station mode sometimes works, and sometimes not. I guess it depends on the router and a bunch of advanced network stuff that I dont understand. Nevertheless: this means for a user who wants to access the ESP32 webserver page, he/she must know the IP. How do you solve this when that user does not have access to the serial print nor some ESP-attached display?

    A static IP address would be a great solution, but it is just not reliable enough. I have also tried with mDNS and also that was unreliable (worked on iPhone but not Android).

    This is a use case where I would give a project as a gift to someone who doesnt know Arduino and can’t expect them to read Serial monitor or something like that. I haven’t found a true solution to this problem anywhere. How do you solve it?

    Reply
    • Hi Amin,
      normally a DHCP server on the router supplies IP addresses to the clients from a list of allowed addresses. If you set a static IP address in Station mode, this address must be excluded from the list of addresses the router is allowed to supply, otherwise two same addresses clash. Look in the configuration of your router, search for a DHCP entry and exclude your static IP address. Then static IP addresses are really reliable.

      Reply
      • Thank you for your reply Peter. That would totally make static IP addresses work. But my use case is when I give a project as a gift to someone to use in their home network. I can’t expect them (think your mother haha) to go in and mess in the config of their router. I am looking for a solid and simple solution that does not require reading the serial monitor, or attaching a screen (one time use only to find out the IP!) nor changing their router settings. Most people can’t do this and I want to build something for most people.

        Reply
        • Hi Amin,
          in your case you cannot go with a static IP address. You know the MAC (physical) address of your ESP32 board or you can set the MAC address of the ESP32 to your own address (see RUI’s tutorials for details). Then you need to identify the dynamic IP address corresponding to your MAC address within your client app. This is done by the ReverseARP protocol RARP. On Windows or Linux use “arp -a” which creates a list of all MAC addresses and the corresponding IP addresses in your network. See https://www.pcwdld.com/find-device-or-ip-address-using-mac-address for details.
          Peter

          Reply
        • If you don’t want to attach an LCD or TFT screen to your device, you can flash a simple LED to reveal the last byte of the IP address, going through the 3 decimal digits that make it up for example… assuming the person knows the address class of their private network (which they can view on any of their connected devices) 😋

          Reply
  11. Hi
    Thank you for publishing the article. Regarding the while loop I have a need to modify the while loop so it checks for two conditions for example
    (WiFi.status() != WL_CONNECTED) or (WiFi.status() != WL_NO_SSID_AVAIL)

    Could you advice me of the best approach

    Best Regards

    Reply
  12. Is there a way to show my gratitude, Rui and Sara? The books and tutorials that you produce are nothing short of fantastic. It’s a joy to work on a project that incorporates your work knowing that you have published information and code that is accurate and complete. You two are making a huge impact on the world of IOT and data networking that will advance the technology as well as advance the knowledge of thousands of us nerds! Thank you for what you do for the world every day!

    Reply
  13. Hi Sara & Rui,
    Thank you for another great tutorial. You guys are really the best on the ESP tutorials for many reasons. Please forgive the length of this little comment. Note to all of you: I do not make a dime writing what I post below. I just love the work that Rui & Sara are doing and want them to keep doing it forever!

    I have a stressful job that I actually love, (regulatory consultant helping people comply with impossible regulations), but as far as concentration zen time to re-load a kinder gentler me, reading & following the Random Nerds tutorials & courses is the best stress relief I have had in 50 years (neglecting some obvious things like swimming, fishing, time with wife, and family gatherings, etc.) No kidding!

    Note to Bob above about support. You can’t go wrong purchasing RN courses at their https://rntlab.com/shop/.

    The Random Nerd courses are very comprehensive, better organized, easy to follow, inexpensive, and just pure excellence compared to other courses on similar subjects. They have on-line and pdf version of the courses, as well as great videos for all the course material. They are the best organized courses with useful examples. Every time I have had a relevant question and email either Rui or Sara, they respond with really helpful info that is to the point and relevant. I just wish I had more time to spend reading their stuff and using it on my little projects.

    As far as the boards used on their ESP32 courses, even though Rui & Sara mostly use the ESP-WROOM-32 varieties (30 pin and 38 pin Devkits mostly), their code runs on every ESP32 board that I have tried it on, by just paying attention to the pinout for the board and adapting the code a little.

    Hope I did not miss Amin’s point, but maybe a suggestion for Amin: if you try out their code on a couple of ESP32’s with little on board displays, even though they are a little more expensive, like the M5Sticks, M5 Core, LILIGO TTGO T-Display, or LILIGO TTGO TS, or HelTec WiFi Kit V2, or even the MorphESP240, (Definitely use Rui & Sara’s Maker Advisor at https://makeradvisor.com/ for where to get a ESP32 board with display for the best price), then you will find one for a reasonable price that you can try your code on. Then when you are satisfied with how it works, just port it over to a very inexpensive DevKit V1 or whatever ESP board you like.

    One last thing, I looked and seem to remember a Random Nerds tutorial for ESP32 autoconnect (initial connection and adding to existing code, something like the stuff on Hackster, IOTDesignpro, Circuit Digest, or Instructables:
    https://github.com/Hieromon/AutoConnect
    https://github.com/evert-arias/esp32-wifi-autoconnect
    https://github.com/zhouhan0126/WIFIMANAGER-ESP32/tree/master/examples/AutoConnect
    And a great one by Frenoy Osburn, https://www.bitsnblobs.com/add-wifi-autoconnect-to-esp32-esp8266-boards
    https://www.hackster.io/BnBe_Club/using-wifi-autoconnect-with-esp8266-esp32-boards-22c710

    Anyway, they work mostly, but I pray that Rui & Sara do a tutorial on that, because it it will be far superior to what I have tried so far. Maybe they have & I just can’t find it. Anyway, I might be confusing it with another source. Don’t get me wrong, the other authors tutorials & githubs are fine. Nonetheless, the way Rui & Sara do their stuff blows everyone else out of the water.

    Thanks again Random Nerds. I wish words were sufficient to express my appreciation. I’ve already purchase and read all you courses (except 2).

    Reply
  14. Small correction

    Because the ESP32 doesn’t connect further to a wired network like your router, it is called soft-AP (soft Access Point)

    soft-AP stands for ‘software enabled Access Point’ meaning; the feature is emulated in software. It’s nothing to do with the fact it’s not connected to a wired network (In fact you can connect a softAP to a wired network; this and it’s still a softAP)

    Reply
  15. I’m just starting to use the Espressif ‘ESP-S2-SAOLA-1’ (ESP32-S2-WROVER)

    I copied your demo but I’m not able to connect to my private WiFi using ‘SAOLA’ board. Using a different ESP32 board works fine.

    Software never goes in WL_CONNECTED
    ‘ssid’ and ‘password’ are correct.

    Serial.print(“Connecting to “);
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }

    SAOLA board works fine for other functionality, also ‘Access Point’ implementation is fine! Only the ‘WIFI_STA’ give me trouble.

    What’s wrong?
    Something relate to ESP32-S2?

    Thanks.

    Reply
  16. Hi, I’ve just started playing with ESP32s and this site has been a nice resource for me. I know that WPA2* is not very secure and I have discovered that EspressIf has added support for WPA3. I am however not sure if the Arduino IDE supports this yet, or even if they are working on adding this support.

    Do you happen to know what is going on with WPA3 and Esp32 in relation to Arduino IDE?

    Thanks!

    Reply
  17. Great tutorial!
    Thanks for your work.
    but, do you have any example “WiFi.mode (WIFI_AP_STA)” ??
    For example, the user with a new ESP at home uses AP mode to select his home network and configure his email, after saving these data ESP restarts and enters Station operating mode connecting to this wifi network previously configured for send temperature data to a server using the e-mail registered as data, if it is necessary to reconfigure the wifi network again it should go back to the menu with the available wifi networks, it could have a physical button for this or a config/use jumper.

    Reply
  18. Thank you for this useful sample AP code.
    It works with my WROOM board, except that ‘channel’ and ‘ssid_hidden’ parameters do nothing. I always get channel 1, and the SSID is always visible.

    Seems the WiFi library is for 8266 devices, so thought I’d try for something more specific to the hardware. Unfortunately Espressif want us to use ESP-IDF. I don’t know how to apply their code to the Arduino IDE. (Could try with Eclipse, but it’s a bit clumsy.)
    So I’ll have a play with the Esp32WifiManager and see what happens.

    I was wondering if I could influence the signal strength, hence wanting to not use channel 1, which is pretty crowded in my house. Maybe not. Trying external antennas soldered to the boards. That helped a bit with a LilyGo ESP32+LCD board.

    Reply
  19. An update on my previous comment:
    The ‘channel’ and ‘ssid_hidden’ parameters to WiFi.softAP() do take effect if the password is long enough. (A password of less than 8 chars doesn’t work, it is equivalent to no password.)

    Reply
  20. Excellent tutorial
    My need is a bit similar to. ‘Admin’

    I have an air quality sensor. CO2 VOCs etc.
    Set as an AP

    I want to go into a public place that has an open WiFi.

    Scan for the open WiFi.
    Select it with a cellphone
    Then my unit would connect to that.

    Ive spoken to some of the places i visit and so everyone would permit me to rest the air.

    Reply
  21. great tutorial!
    my system is not able to find the definition for this: WiFiEventInfo_t
    I am including these headers: ESP8266WiFi.h ESPAsyncTCP.h ESPAsyncWebServer.h
    any suggestions?

    Reply
  22. Hi, this is very useful information. I wish I had found your article a few weeks ago when I started with my ESP32-C3 project. I’m working on a project that involves collecting CSI data between chips for distance ranging and I can collect CSI data at the moment only through the chips connecting one as station, the other as AP. It would be better if I could get the chips to broadcast packets and listen for these to generate the CSI data, rather than make individual connections so that the distance estimation can occur for multiple chips. Is this possible?

    Reply
  23. ATTN: Arduino IDE libraries now seem to require different constant and type names.

    This code does not work when using the Arduino IDE (Nov 2021). The constant names that work are different and (to add to the confusion) these (SYSTEM) names are still defined. For example, instead of
    SYSTEM_EVENT_STA_CONNECTED
    use ARDUINO_EVENT_WIFI_STA_CONNECTED.

    You can find all of the connect constants and types (some type names are also different) here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiGeneric.h

    Thanks for all the great tutorials.

    Cheers,

    –joey

    Reply
  24. Is there a simple speed test I can run to test signal strength/quality? I’m trying to run an app where a camera image captured is uploaded to a cloud drive, but get beacon timeouts that trash the wifi connection. So I’m trying to diagnose things.

    Reply
  25. ESP32 ESP-Now and channels
    My ESP32 ESP-Now transmitter is always on in my shed, it transmits weather data. It was apparently set to channel 2.
    My ESP-Now receiver is in my workroom and sometimes is turned off for new programming.
    One time the receiver went off IP address and channel. I booted my network system and the receiver channel came back to channel 2.
    I read through the https://randomnerdtutorials.com/esp32-useful-wi-fi-functions-arduino/ article, but didn’t find anything about keeping the channel number between two devices.
    Apparently in the https://randomnerdtutorials.com/esp32-esp-now-wi-fi-web-server/ article it mentioned doing something to the transmitter to change the channel (but I don’t know what).
    Is there a way to make the router set the channel # on the receiver?
    Or is there another way?
    Thanks

    Reply
  26. As I see ESP32 supports explicit LongRange mode (ofcourse at a cost of compromised band width), but how to enable it?

    Reply
  27. Hi, I made everything like here, but I have an error: initWiFi() was not declared in this scope. Why? I copy everything like in ebook and it doesn’t work((

    Reply
    • Hi.
      what code are you using?
      Where are you calling the initWiFi() function and where is it declared?
      Regards,
      Sara

      Reply
  28. Dear all, I have a strange problem, I have this code for a DOIT ESP32 DEV KIT V1:

    // Connect to Wi-Fi
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    Inside setup(), and I have no problems at all to compile it.
    If I import the same file from PlatformIO, I get the following error:

    C:/Users/josem/Documents/PlatformIO/Projects/220726-183829-esp32doit-devkit-v1/src/_20220724_Telegram_Control_ESP32_ESP8266.ino: In function ‘void setup()’:
    C:/Users/josem/Documents/PlatformIO/Projects/220726-183829-esp32doit-devkit-v1/src/_20220724_Telegram_Control_ESP32_ESP8266.ino:262:7: error: ‘class WiFiClass’
    has no member named ‘mode’
    WiFi.mode(WIFI_STA);

    Any suggestion about?

    Reply
    • I mean I have no problem to compile, under Arduino IDE, but at opposite, I’m not able to compile inside VSC – PlatformIO

      Reply
      • Yes, I think so, this is my PlatformIO.ini

        [env:esp32doit-devkit-v1]
        platform = espressif32
        board = esp32doit-devkit-v1
        framework = arduino
        lib_extra_dirs = ~/Documents/Arduino/libraries

        ; Serial Monitor options
        monitor_speed = 115200

        Reply
  29. This tutorial was most helpful in solving a Wi-Fi connection problem. I tried the function ‘initWiFi()’ and although the AP was recognized in the scan, I could not connect to it. The problem was solved by increasing the delay to 2000. Some routers require more time than is allowed by delay(1000) to respond. May I suggest increasing the delay value in the text.

    Reply
  30. Thank you very much for the excellent content.

    Where they get instructions such as: “onEvent” , “setHostname” and events.

    I’m searching the entire WiFi library in the WiFi folder and I can’t find those events that describe the ESP32. In WiFiGeneric.h there are events but they are not called the same.

    The parameters of the following line also call my attention:

    void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info)

    They have some list or guide of all the functions and parameters that can be used.

    Thank you very much in advance.

    PS: I am from Argentina and all the comment was translated by google translator

    Reply
  31. I have been trying to convert all my monitor output to standard C++ format (i.e. “cout <<” ) and I have encountered a strange problem. When displaying the results of a WiFi scan, I get different output from Serial.print than from cout as follows;

    Serial.print(WiFi.SSID(i) – “dnbWiFi” Which is correct
    Cout << WiFi.SSID(i) – “1” Which is incorrect (one or 0x31)

    In fact, I get the same output (‘1’) with cout for all values of i but the Serial.print output is always correct. I also get the correct results for WiFi.SSID(i)).length();

    To make things even more confusing, WiFi.RSSI(i) always prints correctly regardless of the output print method.

    Does anyone have any idea what’s happening here?

    Reply
  32. Great content!
    I am trying to use ESP_NOW between two ESP’s to read the RSSI between them. I have been working on this with no success. Some sites recommend promiscuous mode to get the RSSI from the header. I am using the Arduino IDE to write the sketches. Any help would be appreciated.

    Reply
      • I have a working weather station using ESP32 boards using ESP_Now.
        One of the things I have to do in the transmitter code is this:
        #include <WiFi.h>
        #include <Wire.h>
        #include <esp_now.h>
        #include <esp_wifi.h>
        #include <Adafruit_Sensor.h>
        #include <Adafruit_BME280.h>

        esp_now_peer_info_t peerInfo; // This is important. Keep this early

        Hope this helps a little.

        Reply
  33. Hello,
    i’m looking to understand why the ESP32 still connected to low rssi AP instead the near one wit strong rssi. Roaming function is supported and working ? i try with google but it’s not so clear situation. Honestly i need also to understand if depend from local WiFi network that seem need to support roaming function.
    Suggestion ?

    Reply

Leave a Reply to Peter St. Cancel reply

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.