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.
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):
- Wi-Fi Modes: station, access point and both (station + access point);
- Scan Wi-Fi networks;
- Connect to a Wi-Fi network;
- Get Wi-Fi connection status;
- Check Wi-Fi connection strength;
- Get ESP32 IP address;
- Set an ESP32 Static IP address;
- Disconnect Wi-Fi;
- Reconnect to Wi-Fi after connection is lost;
- ESP32 Wi-Fi Events;
- Reconnect to Wi-Fi Network After Lost Connection (Wi-Fi Events);
- ESP32 WiFiMulti
- Change ESP32 Hostname.
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.
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.
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.
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);
}
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
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:
Value | Constant | Meaning |
0 | WL_IDLE_STATUS | temporary status assigned when WiFi.begin() is called |
1 | WL_NO_SSID_AVAIL | when no SSID are available |
2 | WL_SCAN_COMPLETED | scan networks is completed |
3 | WL_CONNECTED | when connected to a WiFi network |
4 | WL_CONNECT_FAILED | when the connection fails for all the attempts |
5 | WL_CONNECTION_LOST | when the connection is lost |
6 | WL_DISCONNECTED | when 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:
}
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).
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()
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;
}
}
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):
0 | ARDUINO_EVENT_WIFI_READY | ESP32 Wi-Fi ready |
1 | ARDUINO_EVENT_WIFI_SCAN_DONE | ESP32 finishes 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 access point v6IP addr is preferred |
19 | ARDUINO_EVENT_WIFI_STA_GOT_IP6 | ESP32 station v6IP addr is preferred |
19 | ARDUINO_EVENT_ETH_GOT_IP6 | Ethernet IPv6 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 |
25 | ARDUINO_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);
}
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);
}
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 & Sara Santos - Random Nerd Tutorials
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
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Change the hostname
const char* hostname = "esp32-node-temperature";
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(hostname);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.print("\nESP32 IP Address: ");
Serial.println(WiFi.localIP());
Serial.print("ESP32 HostName: ");
Serial.println(WiFi.getHostname());
Serial.print("RRSI: ");
Serial.println(WiFi.RSSI());
}
void setup() {
Serial.begin(115200);
initWiFi();
}
void loop() {
// put your main code here, to run repeatedly:
}
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.
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:
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
Hi,
You can change ESP32 hostname using commands like this:
String MA02_ID = “MA02_09”;
WiFi.setHostname(MA02_ID.c_str()); //define hostname
Hi Werner,
Try this, it should do the trick 😉
WiFi.mode(WIFI_MODE_STA);
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(YOUR_HOSTNAME);
WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASS);
Hi,
Unfortunately doesn’t work for me – tried it on 2 different boards and with different sized hostnames. Small hostnames just continue to show expressif on network scan and larger hostname just gives a blank 🙁
Regards, Sandy
Sorry to hear that…
It works perfectly on my side!
Even with a rather long name with spaces.
Try to refresh the DHCP client list on your router.
Hi,
Sorry for the delay.
I rebooted my router and lo and behold the changed hostnames appeared – thank you 🙂
Sandy
I wanted to post an image to illustrate my point in my last comment, but it didn’t work. You can see it by clicking on the link.
The arduino-esp32 framework has just been updated to version 1.0.5. Some of the fixes include the following:
ad4cf146 Rework setHostname for WiFi STA
5de03a39 Fix WiFi STA config IP to INADDR_NONE results in 255.255.255.255
See if this solves your problem?
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?
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() {}
Sorry… formatting with Markdown didn’t work properly :-/
But you should be able to format the code in your favorite editor.
I fixed that by publishing the code on GitHub Gist 😉
Hi Stéphane,
Thanks for sharing this.
Regards,
Sara
Hi Sara, I have a question: Could ESP32 work running like an acces point and mqtt cliente at the same time?
thanks
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
hi Sara ,hi Rui
first , thank you for these tutorials, priceless
the problem i am having with esp32 WiFi connection is that unless you connect through a computer and read the ip address from serial monitor , then you dont know the address to search for
off course you can program it with an static IP as long as you use it on your network, but i am not sure what will happen if you connect it to another network
i have also found out that although my esp32 dev module is connected to Wifi and i can reach it through browser, it is hidden in the routers wifi list
recently i installed FluidNC on a similar unit and i can reach it by simply putting “FluidNC.local” in the search bar
i am wondering if a similar approach can be implemented in general
can i have your thoughts, please?
and finally why is esp32 hidden in wifi network
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?
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
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!
+1 for an example of how the combination WIFI_AP_STA works.
Thanks,
Dennis
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.
Great article. Woyld have liked to ser how to use both modes to make a WiFi extender on ESP32. Thete is little info on this on the web although i know it is possible.
Yes, Need this WiFi extender
Check this sentences pls: “Or, you can call WiFi.diconnect() followed by WiFi.begin(ssid,password)”. Must WiFi.disconnect
Hi.
Thanks. You are right.
It’s fixed now!
Regards,
Sara
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.
Hi,
Really good – thanks!
I would echo Dave’s request for an example using the soft_AP and STA modes together.
Sandy
Thanks for the suggestion.
I’ll add that to my list.
Regards,
Sara
hi sara,
Great Tutorial! indeed. is it possible to connect esp32 with a hidden network and enterprise network? if yes can you suggest the way.
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?
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.
Hi.
Thanks for the suggestion.
In fact, we have a project like that in our most recent eBook: https://randomnerdtutorials.com/build-web-servers-esp32-esp8266-ebook/
I’ll probably release that project or a simplified free version of that project soon.
Regards,
Sara
Very helpful artical. Thank you very much
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.
Thanks for sharing that.
I’ll add it to the tutorial in the next update.
Regards,
Sara
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
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?
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.
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.
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
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) 😋
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
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!
Hi Bob.
Thank you so much for your nice words.
I’m glad you enjoy our tutorials and eBooks.
There are several ways to support our work. See here: https://randomnerdtutorials.com/about/.
Regards,
Sara
I was looking for same type of content. Thanks for doing enhanced research for us. I will try it and give my feedback again.
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).
Hi.
Thank you so much for your nice words and for supporting our work.
I’m speechless about your awesome testimonial. I just want to say “Thank you!”. It feels nice to know that people find value in our work.
The randomnerds website is not ours. I’ve deleted that line in your comment to not confused other people.
These are the sites we own:
https://rntlab.com/
https://randomnerdtutorials.com/
https://makeradvisor.com/
Once again, thank you.
Regards,
Sara
I think the tutorial you are looking for is this one: https://randomnerdtutorials.com/solved-reconnect-esp32-to-wifi/
Regards,
Sara
Small correction
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)
have any example with “WiFi.mode (WIFI_STA_AP)”???
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.
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!
Sinds arduino core 2.0, WPA3 is supported. I can’t find a tutorial yet but hopefully soon here
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.
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.
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.)
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.
Hi.
Take a look at WiFiManager: https://github.com/zhouhan0126/WIFIMANAGER-ESP32
Regards,
Sara
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?
Hi.
This tutorial is for the ESP32, not for the ESP8266.
Regards,
Sara
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?
Hi.
Take a look at ESP-NOW and ESP-MESH communication:
– https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/
– https://randomnerdtutorials.com/esp-mesh-esp32-esp8266-painlessmesh/
Regards,
Sara
My understanding is that ESP-NOW won’t provide CSI data, but I haven’t played around with it yet myself. Thanks for the reply.
ESP-MESH looks promising thanks!
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
Hi.
Thanks for pointing that out.
I’ll test it soon and update the tutorial if needed.
Regards,
Sara
WPA3 is nog supported in arduino core 2.x. Can the tutorial updated with this?
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.
Hi.
Check example 5: https://randomnerdtutorials.com/esp32-useful-wi-fi-functions-arduino/#5
Regards,
Sara
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
Hi.
In the ESP-NOW Web Server example, there’s a section that shows how to put the sender and receiver on the same channel automatically.
That solution was presented to us by one of our readers. Maybe it is better to take a look at his explanation and examples here: https://github.com/m1cr0lab-esp32/esp-now-network-and-wifi-gateway
Regards,
Sara
As I see ESP32 supports explicit LongRange mode (ofcourse at a cost of compromised band width), but how to enable it?
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((
Hi.
what code are you using?
Where are you calling the initWiFi() function and where is it declared?
Regards,
Sara
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?
I mean I have no problem to compile, under Arduino IDE, but at opposite, I’m not able to compile inside VSC – PlatformIO
Hi.
Did you have the right board in the platformio.ini file?
Regards,
Sara
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
Do you thing that it could be a good idea to publish it on Facebook too?
I don’t think it is necessary.
However, if you’re not able to solve the issue, you can search for further help.
Regards.
Sara
Why are you using this:
lib_extra_dirs = ~/Documents/Arduino/libraries
?
I’ts not because of me, just appeared when I imported the project from Arduino
I suggest creating a new project from the start using VS Code.
Regards,
Sara
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.
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
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?
How to get Connected Speed ?
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.
I got it to work. Thanks
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.
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 ?
Hi, great tutorials. Much appreciated.
Wondering if you could answer an ESP qustion puzzlings me for sometime.
I recall ESP8266’s only core, and, ESP32’s first core constrantly runs wifi stack.
When a connection drops:
(a) does the wifi stack on core/firmware re-establishes the connection automatically?
(b) or, it is user’s responsibiility to check connection constantly and reconnect in a loop, if necessary?
(c) or, when wifi library used, does the library makes further connections automatically?
Any comments? Thanks,.
Hello, congratulations for your site, thanks to which I start to learn things in the field of ESP32. I have several questions about WiFi (and in particular the use of WPS). My configuration is as follows: I have an ESP32, an I2C OLED screen, and a push button. The hardware configuration works, I launched several basic examples (with SSID and Password) which work perfectly.
What I want now to obtain: after pressing the WPS button on my box, and by pressing the push button associated with the ESP32, I want to retrieve the SSID and the password:
* Have you developed such an example (ESP32 + push button) in your site?
* How to use the WPS.ino example in practice?
Thanks for your help