Connect to WiFi network
#include <WiFi.h>
How to connect to a WiFi network with the ESP32
The built-in WiFi.h library will allow us to use the WiFi features of the ESP32
board easily.
The ESP32 has 2 WiFi modes:
STATION ( WIFI_STA ) : The Station mode (STA) is
used to connect the ESP32 module to a WiFi access point. The ESP32 behaves like
a computer that is connected to our router. If the router is connected to the
Internet, then the ESP32 can access the Internet. The ESP32 can behave as a
client: make requests to other devices connected to the network, or as a server:
other devices connected to the network will send requests to the ESP32. In both
cases, the ESP32 can access the Internet.
AP (Access Point) (WIFI_AP ): In Access Point mode
, the ESP32 behaves like a WiFi network (a bit like a router): other devices can
connect to it. In this mode, the ESP32 is not connected to any other network and
is therefore not connected to the Internet. This mode is more computationally
and energy-intensive (the ESP32 board will heat up) since the ESP32 has to
simulate a full WiFi router (Soft AP). The latency and the bandwidth will be
less efficient than in a classic router.
Note
The ESP32 is, by default in STATION mode.
For mode selection :
In general, we use the STATION mode. We can access the Internet to retrieve
information from an API, have a home automation server with sensors …
The AP mode is usually used temporarily to enter the credentials of the WiFi
network (SSID and password). It can also be used to have a separate network from
your home network and not be connected to the Internet.
Connecting to a Wi-Fi Access Point
The code to connect to his AP is as follows:
/*F********************************************************************
*
**********************************************************************/
#include
//************************* DEFINES ************************************
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.mode( WIFI_STA ); // Optional
WiFi.begin( ssid, password );
Serial.println( "\nConnecting" );
while( WiFi.status() != WL_CONNECTED )
{
Serial.print(".");
delay(100);
}
Serial.println( "\nConnected to WiFi network");
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
Important
You need to change "yourNetworkName" to the name of your WiFi network and
"yourNetworkPassword" to your network password.
Terminal output
Connecting
................
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129
Tip
An easy way to have a WiFi access point to test the code is by sharing a WiFi
connection from your smartphone.
The code functions as follows:
We must include the WiFi.h library.
Then we enter the name of the network and its password.
We put the ESP32 in STATION mode with the function WiFi.mode(WIFI_STA)
The ESP32 tries to connect to the Wi-Fi network using the function
WiFi.begin( ssid, password)
The connection is not instantaneous! It is therefore necessary to regularly
check the connection status: as long as the ESP32 is not connected to the
network, we will remain blocked inside the while loop. We add a slight delay to
avoid constantly checking the status.
Once the connection has been established, the local IP address of the ESP32
on this network will be displayed.
If it is an open network (without a password), then the code becomes simpler:
/*F********************************************************************
*
**********************************************************************/
#include
//************************* DEFINES ************************************
const char* ssid = "yourNetworkName";
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.begin( ssid );
Serial.println( "\nConnecting");
while( WiFi.status() != WL_CONNECTED )
{
Serial.print(".");
delay( 100 );
}
Serial.println( "\nConnected to WiFi network");
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
Note
Storing logins and passwords in clear text in the code is a bad practice.
However, doing so simplify tutorials.
Get WiFi network information
You can get information about the network once you are connected to it:
- WiFi signal strength (RSSI) with the WiFi.RSSI() function
- The MAC address of the WiFi network with WiFi.BSSIDstr() or WiFi.macAddress()
- The local IP address of the ESP32 assigned by the DHCP server of the WiFi
network with WiFi.localIP()
- The local IP address of the WiFi network (gateway) with WiFi.gatewayIP()
(usually 192.168.0.1)
- The subnet mask with WiFi.subnetMask() (usually 255.255.255.0)
The code below displays all this information:
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
#define BAUD 9600
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
void get_network_info();
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.begin( ssid, password);
Serial.println( "\nConnecting");
while( WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
Serial.println( "\nConnected to the WiFi network");
get_network_info();
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
/*F********************************************************************
*
**********************************************************************/
void
get_network_info()
{
if( WiFi.status() == WL_CONNECTED)
{
Serial.print( "[*] Network information for ");
Serial.println( ssid);
Serial.println( "[+] BSSID : " + WiFi.BSSIDstr());
Serial.print( "[+] Gateway IP : ");
Serial.println( WiFi.gatewayIP());
Serial.print( "[+] Subnet Mask : ");
Serial.println( WiFi.subnetMask());
Serial.println( (String)"[+] RSSI : " + WiFi.RSSI() + " dB");
Serial.print( "[+] ESP32 IP : ");
Serial.println( WiFi.localIP());
}
}
Terminal output
Connecting
..............
Connected to the WiFi network
[*] Network information for HUAWEI_**
[+] BSSID : F0:43:47:32:1F:4D
[+] Gateway IP : 192.168.43.1
[+] Subnet Mask : 255.255.255.0
[+] RSSI : -25 dB
[+] ESP32 IP : 192.168.43.129
Debug Wi-Fi connection issues
By monitoring the connection status
We can know the status of the WiFi connection with the function WiFi.status().
This function returns an integer according to the current status of the
connection.
The possible statuses are :
WL_IDLE_STATUS : This is the default status before trying to connect to a
network.
WL_SCAN_COMPLETED : The WiFi network scan is completed.
WL_NO_SSID_AVAIL : The ESP32 cannot find the name of the WiFi network.
Either the network is too far from the ESP32, or the name (SSID) of the network
is incorrect.
WL_CONNECT_FAILED : The ESP32 cannot connect to the designated WiFi network.
WL_CONNECTION_LOST : The WiFi connection to the network is lost. If this
error occurs repeatedly, it may be a power problem with the ESP32.
WL_CONNECTED : The ESP32 is connected to the WiFi network.
WL_DISCONNECTED : The ESP32 is disconnected from the WiFi network.
Code that displays the status of the WiFi connection
/*F********************************************************************
*
**********************************************************************/
#include
//************************* DEFINES ************************************
#define BAUD 9600
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
String get_wifi_status( int status );
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin(115200);
delay(1000);
int status = WL_IDLE_STATUS;
Serial.println("\nConnecting");
Serial.println(get_wifi_status(status));
WiFi.begin(ssid, password);
while(status != WL_CONNECTED){
delay(500);
status = WiFi.status();
Serial.println(get_wifi_status(status));
}
Serial.println("\nConnected to the WiFi network");
Serial.print("Local ESP32 IP: ");
Serial.println(WiFi.localIP());
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
/*F********************************************************************
*
**********************************************************************/
String
get_wifi_status( int status )
{
switch( status )
{
case WL_IDLE_STATUS:
return "WL_IDLE_STATUS";
case WL_SCAN_COMPLETED:
return "WL_SCAN_COMPLETED";
case WL_NO_SSID_AVAIL:
return "WL_NO_SSID_AVAIL";
case WL_CONNECT_FAILED:
return "WL_CONNECT_FAILED";
case WL_CONNECTION_LOST:
return "WL_CONNECTION_LOST";
case WL_CONNECTED:
return "WL_CONNECTED";
case WL_DISCONNECTED:
return "WL_DISCONNECTED";
}
}
Examples of possible scenarios
Successful connection:
Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_CONNECTED
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129
SSID not found:
Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_WORK
Wrong password:
Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_WORK
By restarting the ESP32
Occasionally, the ESP32 may temporarily fail to connect to the WiFi for unknown
or strange reasons. The best solution is to say that after n seconds, if the
ESP32 still hasn’t connected to WiFi, we restart the ESP32. Just add a timeout
and use the ESP.restart() function to restart the ESP32 from the code.
Here is an example that will restart the ESP32 after 10 seconds if it is still
not connected to WiFi.
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
#define BAUD 9600
#define CONNECTION_TIMEOUT 10
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.mode( WIFI_STA ); // Optional
WiFi.begin( ssid, password );
Serial.println( "\nConnecting" );
int timeout_counter = 0;
while( WiFi.status() != WL_CONNECTED )
{
Serial.print( "." );
delay( 200 );
timeout_counter++;
if( timeout_counter >= CONNECTION_TIMEOUT*5)
ESP.restart();
}
Serial.println( "\nConnected to the WiFi network" );
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
The ESP32 is reset after 10 seconds in case of connection failure from the code
with the the``SW_CPU_RESET`` flag during the boot.
Connecting
.......................................................
ets Jun 8 2016 00:22:57
rst:0xc ( SW_CPU_RESET ),boot:0x13 ( SPI_FAST_FLASH_BOOT )
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac
Connecting
.......
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129
Change Wi-Fi channel
If the ESP32 has difficulty connecting to the WiFi depending on the period (or
time slot), it may be related to the Wi-Fi channel chosen by your Acces Point.
In fact, even if the Wi-Fi frequency is at 2.4GHz, the AP uses many subbands
around 2.4GHz, called channels, to reduce the traffic. This makes it possible to
have many different Wi-Fi routers in a very close space in buildings without
them interfering with each other.
For France, there are 14 channels available. The available channels vary
according to the country. In general, the channel is chosen automatically by the
router (in auto ), depending on the other channels used by the AP around. Except
that, in practice, the routers are always stuck on the last channels, 12, 13 and
14
One solution is to change the channel number used by the router to number 1, 6
or 11, for example. This change is done via the router’s administrator interface
, usually on IP 192.168.0.1 .
If you use a lot of Wi-Fi-connected IoT objects, I recommend having a second
Wi-Fi router to separate home use from IoT use. You shouldn’t have any more
Wi-Fi connection issues by choosing channel 1 or 6 for the IoT sensor router and
a channel between 11 and 14 for the other router.
Advance WiFi network stuffs for the ESP32
Assign a static IP address
The local IP address of the ESP32 has been assigned automatically by the
router’s DHCP server. It is convenient to have an IP address automatically on
the computer because we do not have to enter it manually. The disadvantage (or
advantage, depending on the case) is that the IP address is dynamic: it can
change. This can become annoying if, for example, as soon as the ESP32 is
restarted (or the DHCP lease is expired), the IP address changes while a web
server is running on the ESP32. We would have to find the IP of the ESP32 every
time. We can overcome this problem by setting the IP address of the ESP32 on the
network. To do this, use the WiFi.config(ip, dns, gateway, subnet) function.
The parameters to be filled in are :
IP : The IP address you wish to assign.
DNS : Service that links a URL to an IP. By default, we use the DNS server
of the router: so we indicate the same address as the router (in general
, 192.168.0.1).
GATEWAY : This is the IP address of the router (usually 192.168.0.1)
SUBNET : Subnet mask (usually 255.255.255.0)
Note
You need to know the router’s IP address: the easiest way is to use the code
that displays the WiFi network information in the serial monitor.
In this example, using the WiFi connection sharing of a phone, the router IP
address is 192.168.43.1. I choose to have the following static IP 192.168.43.42
for the ESP32.
Code to set the IP address of the ESP32
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
IPAddress ip(192, 168, 43, 42);
IPAddress dns(192, 168, 43, 1);
IPAddress gateway(192, 168, 43, 1);
IPAddress subnet(255, 255, 255, 0);
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.config( ip, gateway, subnet, dns );
WiFi.begin( ssid, password );
Serial.println( "\nConnecting" );
while( WiFi.status() != WL_CONNECTED )
{
Serial.print( "." );
delay( 100 );
}
Serial.println( "\nConnected to the WiFi network" );
Serial.print( "[+] ESP32 IP : " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
Warning
It is important to remember not to use an IP address already taken by another
device on the network. You can also assign a fixed IP address linked to the MAC
address directly from the router settings.
For information purposes, we can then ping the computer to the IP 192.168.43.42
to see if the new address has been taken into account:
Result of a ping in the Windows command prompt
Ping the ESP32 from the Windows terminal (cmd.exe)
Note
Suppose you have the error, ping: transmission failure. General failure , there
is probably a software or firewall that disables the use of pings. This can be
the case with VPN clients.
Change the MAC address
In some applications, it can be interesting to change the MAC address of the
ESP32. We can change the MAC address with a few lines of code using the
esp_wifi_set_mac() function.
Note
The MAC address change is temporary and does not replace the original one. You
have to upload a new program to find the original MAC address.
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
#include <esp_wifi.h>
//************************* DEFINES ************************************
#define BAUD 9600
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
uint8_t new_mac[] = {0x60, 0x8B, 0x0E, 0x01, 0x5A, 0x32};
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
WiFi.mode( WIFI_STA );//Needed to change MAC adress
Serial.print( "[+] Current MAC Address: ");
Serial.println( WiFi.macAddress() );
esp_wifi_set_mac( ESP_IF_WIFI_STA, new_mac );
Serial.print( "[+] New MAC Address: ");
Serial.println( WiFi.macAddress() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
Serial terminal :
[+] Current MAC Address: 24:6F:28:BB:2E:E8
[+] New MAC Address: 60:8B:0E:01:5A:32
Code that connects to a Wi-Fi network with a modified MAC address
/*F********************************************************************
*
**********************************************************************/
#include
#include
//************************* DEFINES ************************************
#define BAUD 9600
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
uint8_t new_mac[] = {0x6C, 0x8D, 0xC1, 0x01, 0x5A, 0x32};
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
WiFi.mode( WIFI_STA ); // NEEDED TO CHANGE MAC ADRESS
esp_wifi_set_mac( ESP_IF_WIFI_STA, new_mac );
delay( 1000 );
WiFi.begin( ssid, password);
Serial.println( "\nConnecting");
while( WiFi.status() != WL_CONNECTED )
{
Serial.print( "." );
delay( 100 );
}
Serial.println( "\nConnected to the WiFi network" );
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
A Wireshark capture shows that the address has been changed (here by an Apple MAC address):
wireshark capture changing mac adress esp32
Capture a network frame with Wireshark
Save energy
If you are using an ESP32 in a project that must necessarily use WiFi to work,
it is a good idea to set the ESP32 to Deep Sleep mode in case of connection
failure to minimize power consumption. This is similar to the ESP32 code that
sleeps for 10 seconds between each attempt.
Code that allows putting the ESP32 in Deep Sleep between 2 attempts
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
#include <esp_wifi.h>
//************************* DEFINES ************************************
#define BAUD 9600
#define CONNECTION_TIMEOUT 5 //Time in seconds
#define DEEP_SLEEP_DURATION 10
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
WiFi.begin( ssid, password);
Serial.println("\nConnecting");
int timeout_counter = 0;
while( WiFi.status() != WL_CONNECTED )
{
Serial.print( "." );
delay( 100 );
timeout_counter++;
if( timeout_counter >= CONNECTION_TIMEOUT*10)
{
Serial.println( "\nCan't establish WiFi connexion");
// SETUP TIMER
esp_sleep_enable_timer_wakeup( DEEP_SLEEP_DURATION * 1000000 );
esp_deep_sleep_start(); // START DEEP SLEEP
}
}
Serial.println( "\nConnected to the WiFi network" );
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
Use WiFi events to have an optimized code
Until now, we used to poll the WiFi functions: the ESP32 remains blocked until
it receives an event from the ESP32 WiFi driver. We were doing sequential
programming. Here’s an example:
while( WiFi.status() != WL_CONNECTED )
{
Serial.print( "." );
delay( 100 );
}
We regularly check if the ESP32 has successfully connected to the WiFi network.
While waiting, we’re not doing anything (we could make calculations between 2
polls) and are stuck in the loop.
A more efficient way of doing this is to use event-driven programming. Indeed,
events are generated when the WiFi changes state. The advantage is that we can
execute code automatically depending on the event received. This is very similar
to the interrupts that we use on the GPIO pins. A change of state of the pin
generates an interrupt, which will execute a portion of high-priority code. Here
a change of state of the WiFi generates an event that will also execute a
portion of code.
The basic code for managing events is as follows:
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
#define BAUD 9600
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
void my_function( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.mode( WIFI_STA ); // OPTIONAL
WiFi.onEvent( my_function, WIFI_EVENT_ID );
WiFi.begin( ssid, password );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
/*F********************************************************************
*
**********************************************************************/
void
my_function( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info )
{
//Code
}
We use the function:
WiFi.onEvent(my_function, WIFI_EVENT_ID)
to specify which function will be executed when the event WIFI_EVENT_ID is
detected. WIFI_EVENT_ID must be replaced by the name or number of the event
(see table below). The function my_function() must have the parameters
WiFiEvent_t wifi_event , WiFiEventInfo_t wifi_info even if they are not used.
Event IDs and Corresponding Data Structures
Event ID (legacy event ID) | Event data structure
|
Wi-Fi
|
WIFI_EVENT_WIFI_READY (SYSTEM_EVENT_WIFI_READY) | n/a
|
WIFI_EVENT_SCAN_DONE (SYSTEM_EVENT_SCAN_DONE) | wifi_event_sta_scan_done_t
|
WIFI_EVENT_STA_START (SYSTEM_EVENT_STA_START) | n/a
|
WIFI_EVENT_STA_STOP (SYSTEM_EVENT_STA_STOP) | n/a
|
WIFI_EVENT_STA_CONNECTED (SYSTEM_EVENT_STA_CONNECTED) | wifi_event_sta_connected_t
|
WIFI_EVENT_STA_DISCONNECTED (SYSTEM_EVENT_STA_DISCONNECTED) | wifi_event_sta_disconnected_t
|
WIFI_EVENT_STA_AUTHMODE_CHANGE (SYSTEM_EVENT_STA_AUTHMODE_CHANGE) | wifi_event_sta_authmode_change_t
|
WIFI_EVENT_STA_WPS_ER_SUCCESS (SYSTEM_EVENT_STA_WPS_ER_SUCCESS) | n/a
|
WIFI_EVENT_STA_WPS_ER_FAILED (SYSTEM_EVENT_STA_WPS_ER_FAILED) | wifi_event_sta_wps_fail_reason_t
|
WIFI_EVENT_STA_WPS_ER_TIMEOUT (SYSTEM_EVENT_STA_WPS_ER_TIMEOUT) | n/a
|
WIFI_EVENT_STA_WPS_ER_PIN (SYSTEM_EVENT_STA_WPS_ER_PIN) | wifi_event_sta_wps_er_pin_t
|
WIFI_EVENT_AP_START (SYSTEM_EVENT_AP_START) | n/a
|
WIFI_EVENT_AP_STOP (SYSTEM_EVENT_AP_STOP) | n/a
|
WIFI_EVENT_AP_STACONNECTED (SYSTEM_EVENT_AP_STACONNECTED) | wifi_event_ap_staconnected_t
|
WIFI_EVENT_AP_STADISCONNECTED (SYSTEM_EVENT_AP_STADISCONNECTED) | wifi_event_ap_stadisconnected_t
|
WIFI_EVENT_AP_PROBEREQRECVED (SYSTEM_EVENT_AP_PROBEREQRECVED) | wifi_event_ap_probe_req_rx_t
|
Ethernet
|
ETHERNET_EVENT_START (SYSTEM_EVENT_ETH_START) | n/a
|
ETHERNET_EVENT_STOP (SYSTEM_EVENT_ETH_STOP) | n/a
|
ETHERNET_EVENT_CONNECTED (SYSTEM_EVENT_ETH_CONNECTED) | n/a
|
ETHERNET_EVENT_DISCONNECTED (SYSTEM_EVENT_ETH_DISCONNECTED) | n/a
|
IP
|
IP_EVENT_STA_GOT_IP (SYSTEM_EVENT_STA_GOT_IP) | ip_event_got_ip_t
|
IP_EVENT_STA_LOST_IP (SYSTEM_EVENT_STA_LOST_IP) | n/a
|
IP_EVENT_AP_STAIPASSIGNED (SYSTEM_EVENT_AP_STAIPASSIGNED) | n/a
|
IP_EVENT_GOT_IP6 (SYSTEM_EVENT_GOT_IP6) | ip_event_got_ip6_t
|
IP_EVENT_ETH_GOT_IP (SYSTEM_EVENT_ETH_GOT_IP) | ip_event_got_ip_t
|
IP_EVENT_ETH_LOST_IP (SYSTEM_EVENT_ETH_LOST_IP) | n/a
|
The following code does the same thing as the code at the very beginning to
connect to a router, but this time with the use of events when connected to a
network.
Code that allows connecting to a router with WiFi events
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
#define BAUD 9600
const char *ssid = "yourNetworkName";
const char *password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
void connected_to_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
void got_ip_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.mode( WIFI_STA ); // OPTIONAL
WiFi.onEvent( connected_to_ap, SYSTEM_EVENT_STA_CONNECTED );
WiFi.onEvent( got_ip_from_ap, SYSTEM_EVENT_STA_GOT_IP );
WiFi.begin( ssid, password );
Serial.println( "\nConnecting" );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
/*F********************************************************************
*
**********************************************************************/
void
connected_to_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info )
{
Serial.println( "\nConnected to the WiFi network");
}
/*F********************************************************************
*
**********************************************************************/
void
got_ip_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info )
{
Serial.print( "Local ESP32 IP: " );
Serial.println( WiFi.localIP() );
}
Console output:
Connecting
.............
Connected to the WiFi network
Local ESP32 IP: 192.168.43.167
You can remove the execution of the function linked to an event during the
execution of the program with wifi.removeEvent( WIFI_EVENT_ID )
A practical use case of events is the possibility of automatically reconnecting
the ESP32 in case of disconnection.
/*F********************************************************************
*
**********************************************************************/
#include <WiFi.h>
//************************* DEFINES ************************************
#define BAUD 9600
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
//************************* PROTOTYPES ************************************
void connected_to_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
void disconnected_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
void got_ip_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info );
//************************* VARIABLES ************************************
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( BAUD );
delay( 1000 );
WiFi.mode( WIFI_STA); // OPTIONAL
WiFi.onEvent( connected_to_ap, SYSTEM_EVENT_STA_CONNECTED );
WiFi.onEvent( got_ip_from_ap, SYSTEM_EVENT_STA_GOT_IP );
WiFi.onEvent( disconnected_from_ap, SYSTEM_EVENT_STA_DISCONNECTED );
WiFi.begin( ssid, password);
Serial.println( "\nConnecting");
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{}
/*F********************************************************************
*
**********************************************************************/
void
connected_to_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info)
{
Serial.println( "[+] Connected to the WiFi network" );
}
/*F********************************************************************
*
**********************************************************************/
void
disconnected_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info)
{
Serial.println( "[-] Disconnected from the WiFi AP");
WiFi.begin( ssid, password);
}
/*F********************************************************************
*
**********************************************************************/
void
got_ip_from_ap( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info)
{
Serial.print( "[+] Local ESP32 IP: ");
Serial.println( WiFi.localIP());
}
Console output:
Connecting
[-] Disconnected from the WiFi AP
[+] Connected to the WiFi network
[+] Local ESP32 IP: 192.168.43.167
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[+] Connected to the WiFi network
Local ESP32 IP: 192.168.43.167
Scanning of surrounding wifi networks

ESP32 program that scans Wi-Fi surroundings router.