ESP32 Events Connecting to WiFi Net
#include <WiFi.h>

From:     https://www.upesy.com/blogs/tutorials/how-to-connect-wifi-acces-point-with-esp32


Connecting to WiFi AP Get WiFi Net Info Debug WiFi Conn Issues Examples of Possible Scenarions
Restarting the ESP32 Change WiFi Channel Advanced ESP32 WiFi Net Info Assign a Static IP
Code Set IP Address of ESP32 Change MAC Address Save Energy WiFi Events to Optimize Code
Applicaiont Example: WiFi Scan ESP32 Event Numbers V2 ESP32 Event Numbers V1 ESP32 Event Connect
Reconn Using Events


How to connect to a WiFi network with the ESP32

(Updated at 01/20/2023)

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:


Note

 The ESP32 is, by default in STATION mode.

For mode selection :




Connecting to a Wi-Fi Access Point The code to connect to his AP is as follows: #include <WiFi.h> const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; /*F******************************************************************** * **********************************************************************/ void setup() { Serial.begin( 115200 ); delay( 1000 ); WiFi.mode( WIFI_STA ); // OPTIONAL WiFi.begin( ssid, password ); Serial.println( "\nConnecting" ); while( WiFi.status() != WL_CONNECTED ) { Serial.print( "." ); delay( 100 ); } Serial.println( "\nConnected to the WiFi network" ); Serial.print( "Local ESP32 IP: " ); Serial.println( WiFi.localIP() ); } /*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: /*F******************************************************************** * AN OPEN NETWORK (WITHOUT A PASSWORD), THEN CODE BECOMES SIMPLER: **********************************************************************/ #include <WiFi.h> //************************* DEFINES ************************************ #define BAUD 9600 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 the 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: The code below displays all this information: /*F******************************************************************** * **********************************************************************/ #include <WiFi.h> //************************* DEFINES ************************************ //************************* PROTOTYPES ************************************ void get_network_info(); //************************* VARIABLES ************************************ const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; /*F******************************************************************** * **********************************************************************/ void setup() { Serial.begin( 115200 ); delay( 1000 ); WiFi.begin( ssid, password ); Serial.println( "\nConnecting" ); while( WiFi.status() != WL_CONNECTED ) { Serial.print("."); delay(100); } Serial.println("\nConnected to the WiFi network"); get_network_info(); } /*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 : Code that displays the status of the WiFi connection /*F******************************************************************** * **********************************************************************/ #include <WiFi.h> //************************* DEFINES ************************************ #define BAUD 9600 //************************* PROTOTYPES ************************************ String get_wifi_status( int status ); //************************* VARIABLES ************************************ const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; /*F******************************************************************** * **********************************************************************/ void setup() { Serial.begin( BAUD ); 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. /*F******************************************************************** * RESTART ESP32 AFTER 10 SECONDS IF IT IS STILL NOT CONNECTED TO WiFi **********************************************************************/ #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 : 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******************************************************************** * SET THE IP ADDRESS OF THE ESP32 **********************************************************************/ #include <WiFi.h> //************************* DEFINES ************************************ #define BAUD 9600 const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; //************************* PROTOTYPES ************************************ //************************* VARIABLES ************************************ 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: Ping the ESP32 from the Windows terminal (cmd.exe) Result of a ping in the Windows command prompt 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******************************************************************** * CHANGE ESP32 MAC ADDRESS **********************************************************************/ #include <WiFi.h> #include <esp_wifi.h> //************************* DEFINES ************************************ //************************* PROTOTYPES ************************************ **********************************************************************/ 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******************************************************************** * CONNECT TO WiFi NET WITH NEW MAC* **********************************************************************/ #include <WiFi.h> #include <esp_wifi.h> //************************* DEFINES ************************************ #define BAUD 9600 //************************* PROTOTYPES ************************************ //************************* VARIABLES ************************************ const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; 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******************************************************************** * ALLOW PUTTING ESP32 IN DEEP SLEEP **********************************************************************/ #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 ************************************ void my_function( WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info ); //************************* 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 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******************************************************************** * BASIC CODE FOR MANAGING ESP32 EVENTS **********************************************************************/ #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. Warning Depending on the version of the ESP32 port in Arduino code you have installed, the name of the events is different.
ESP32 Event Numbers Ver. 2
Version 2.0x
Liste des évènements Wi-Fi
NumberEvent Name Description
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 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 Old version 1.x

ESP32 Event Numbers Ver. 1
Version 1.0x
WiFi Event Numbers
NumberEvent Name Description
0 SYSTEM_EVENT_WIFI_READY ESP32 WiFi ready
1 SYSTEM_EVENT_SCAN_DONE ESP32 finish scanning AP
2 SYSTEM_EVENT_STA_START ESP32 station start
3 SYSTEM_EVENT_STA_STOP ESP32 station stop
4 SYSTEM_EVENT_STA_CONNECTED ESP32 station connected to AP
5 SYSTEM_EVENT_STA_DISCONNECTED ESP32 station disconnected from AP
6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE the auth mode of AP connected by ESP32 station changed
7 SYSTEM_EVENT_STA_GOT_IP ESP32 station got IP from connected AP
8 SYSTEM_EVENT_STA_LOST_IP ESP32 station lost IP and the IP is reset to 0
9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS ESP32 station wps succeeds in enrollee mode
10 SYSTEM_EVENT_STA_WPS_ER_FAILED ESP32 station wps fails in enrollee mode
11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT ESP32 station wps timeout in enrollee mode
12 SYSTEM_EVENT_STA_WPS_ER_PIN ESP32 station wps pin code in enrollee mode
13 SYSTEM_EVENT_AP_START ESP32 soft-AP start
14 SYSTEM_EVENT_AP_STOP ESP32 soft-AP stop
15 SYSTEM_EVENT_AP_STACONNECTED a station connected to ESP32 soft-AP
16 SYSTEM_EVENT_AP_STADISCONNECTED a station disconnected from ESP32 soft-AP
17 SYSTEM_EVENT_AP_STAIPASSIGNED ESP32 soft-AP assign an IP to a connected station
18 SYSTEM_EVENT_AP_PROBEREQRECVED Receive probe request packet in soft-AP interface
19 SYSTEM_EVENT_GOT_IP6 ESP32 STA or AP or ethernet interface v6IP addr preferred
20 SYSTEM_EVENT_ETH_START ESP32 ethernet start
21 SYSTEM_EVENT_ETH_STOP ESP32 ethernet stop
22 SYSTEM_EVENT_ETH_CONNECTED ESP32 ethernet phy link up
23 SYSTEM_EVENT_ETH_DISCONNECTED ESP32 ethernet phy link down
24 SYSTEM_EVENT_ETH_GOT_IP ESP32 ethernet got IP from connected AP
25 SYSTEM_EVENT_MAX

ESP32 Event Connect 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. /*F******************************************************************** * CODE THAT ALLOWS CONNECTING TO A ROUTER WITH WiFi EVENTS **********************************************************************/ #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, ARDUINO_EVENT_WIFI_STA_CONNECTED ); WiFi.onEvent( got_ip_from_ap, ARDUINO_EVENT_WIFI_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)
Reconn Using Events A practical use case of events is the possibility of automatically reconnecting the ESP32 in case of disconnection. /*F******************************************************************** * AUTO RECONN WITH EVENTS **********************************************************************/ #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, ARDUINO_EVENT_WIFI_STA_CONNECTED ); WiFi.onEvent( got_ip_from_ap, ARDUINO_EVENT_WIFI_STA_GOT_IP ); WiFi.onEvent( disconnected_from_ap, ARDUINO_EVENT_WIFI_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
Application example: Wi-Fi Scan /*F******************************************************************** * Here is a concrete application that scans WiFi networks around: **********************************************************************/ #include "WiFi.h" //************************* DEFINES ************************************ #define BAUD 9600 //************************* PROTOTYPES ************************************ String get_encryption_type( wifi_auth_mode_t encryptionType ); //************************* VARIABLES ************************************ /*F******************************************************************** * **********************************************************************/ void setup() { Serial.begin( BAUD ); WiFi.mode( WIFI_STA ); } /*F******************************************************************** * **********************************************************************/ void loop() { Serial.println( "uPesy WiFi Scan Demo" ); Serial.println( "[*] Scanning WiFi network" ); int n = WiFi.scanNetworks(); // RETURNS NUMBER OF NETWORKS FOUND Serial.println( "[*] Scan done" ); if( n == 0 ) { Serial.println( "[-] No WiFi networks found"); } else { Serial.println( (String)"[+] " + n + " WiFi networks found\n"); for( int i = 0; i < n; ++i ) { // PRINT EACH NETWORK'S SSID, RSSI & WiFi ENCRYPTION Serial.print( i + 1 ); Serial.print( ": " ); Serial.print( WiFi.SSID( i ) ); Serial.print( " (" ); Serial.print( WiFi.RSSI( i ) ); Serial.print( " dB) [" ); Serial.print( get_encryption_type( WiFi.encryptionType( i )) ); Serial.println( "]" ); delay( 10 ); } } Serial.println( "" ); delay( 5000 ); // WAIT BEFORE SCANNING AGAIN } /*F******************************************************************** * **********************************************************************/ String get_encryption_type( wifi_auth_mode_t encryptionType ) { switch( encryptionType ) { case WIFI_AUTH_OPEN: return "Open"; case WIFI_AUTH_WEP: return "WEP"; case WIFI_AUTH_WPA_PSK: return "WPA_PSK"; case ( WIFI_AUTH_WPA2_PSK: r"WPA2_PSK"; case WIFI_AUTH_WPA_WPA2_PSK: return "WPA_WPA2_PSK"; case WIFI_AUTH_WPA2_ENTERPRISE: return "WPA2_ENTERPRISE"; } } Scanning of surrounding wifi networks ESP32 program that scans Wi-Fi surroundings router