[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection
This quick guide shows how you can reconnect your ESP32 to a Wi-Fi network after losing the connection. This can be useful in the following scenarios: the ESP32 temporarily loses Wi-Fi signal; the ESP32 is temporarily out of the router’s Wi-Fi range; the router restarts; the router loses internet connection or other situations.

We have a similar guide for the ESP8266 NodeMCU board:
You may also want to take a look atWiFiMulti. It 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. Read:ESP32 WiFiMulti: Connect to the Strongest Wi-Fi Network (from a list of networks).
Reconnect to Wi-Fi Network After Lost Connection
To reconnect to Wi-Fi after a connection is lost, you can useWiFi.reconnect() to try to reconnect to the previously connected access point:
WiFi.reconnect()Or, you can callWiFi.disconnect() followed byWiFi.begin(ssid,password).
WiFi.disconnect();WiFi.begin(ssid, password);Alternatively, you can also try to restart the ESP32 withESP.restart() when the connection is lost.
You can add something like the snippet below to theloop() that checks once in a while if the board is connected and tries to reconnect if it has lost connection.
unsigned long currentMillis = millis();// if WiFi is down, try reconnectingif ((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 thepreviousMillis andinterval variables. Theinterval 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.
Alternatively, you can also use Wi-Fi 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 is able to handle different Wi-Fi events. 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.
The following events are very useful to detect if the connection was lost or reestablished:
- ARDUINO_EVENT_WIFI_STA_CONNECTED: the ESP32 is connected in station mode to an access point/hotspot (your router);
- ARDUINO_EVENT_WIFI_STA_DISCONNECTED: the ESP32 station disconnected from the access point.
Go to the next section to see an application example.
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 theARDUINO_EVENT_WIFI_STA_DISCONNECTED 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_WIDI_STA_CONNECTED,ARDUINO_EVENT_WIFI_STA_GOT_IP, andARDUINO_EVENT_WIFI_STA_DISCONNECTED, respectively.
When the ESP32 station connects to the access point (ARDUINO_EVENT_WIFI_STA_CONNECTED event), theWiFiStationConnected() function will be called:
WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);TheWiFiStationConnected() 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, theWiFiGotIP() 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), theWiFiStationDisconnected() 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.disconnected.reason); Serial.println("Trying to Reconnect"); WiFi.begin(ssid, password);}Wrapping Up
This quick tutorial shows different ways of how you can reconnect your ESP32 to a Wi-Fi network after the connection is lost.
We recommend that you take a look at the following tutorial to better understand some of the most used ESP32 Wi-Fi functions:
One of the best applications of the ESP32 Wi-Fi capabilities is building web servers. If you want to use the ESP32 or ESP8266 boards to build Web Server projects, you might like our eBook:
We hope you’ve found this tutorial useful.
Thanks for reading.

Recommended Resources
Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.
Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.
Arduino Step-by-Step Projects »Build 25 Arduino projects with our course, even with no prior experience!
What to Read Next…
Enjoyed this project? Stay updated by subscribing our newsletter!
72 thoughts on “[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection”
Hi I guess this might solve my issue! Thanks!
ReplyGreat tutorial! Thanks for that!
ReplyThank you Ruy !!!
ReplyThank you for helping us Sara !!!
ReplyThank you for publishing this. Wifi problems are a significant problem on all remote monitoring systems. This will help solve that. I am working a project to
Reply
Remotely control and test my router and modem using sim7000 cell device. I
Wish you would consider developing a tutorial on this subject, I’m sure it would be helpful to man developers.Thank You. This is great. I tried several programming to reconnect to Wi-Fi Network after lost connection, but didn’t know the Wi-Fi Events. I will try this.
Reply
Greatings from Berlin
Sigigreat job !
Reply
is it working on esp8266 too please ?
Thanks
ByeHi.
Reply
The Wi-Fi library is different for the ESP8266. So, it is not compatible.
I’ll have to write a similar tutorial for the ESP8266.
Regards,
Sarawhile you are awaiting Sara’s ESP8266 tutorial on the matter, there is a crude method of doing this:
if (WiFi.status() == 6)
{
ESP.reset();
}‘6’ means WL_DISCONNECTED
I believe it is also possible to use:
Reply
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
immediately after you get connected the first time, but I have not tried that myself, so maybe best to await Sara’s tutorialHi Ed.
Reply
Yes, you can use
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
Right after connecting to Wi-Fi.
When the connection is lost, it will automatically reconnect.
Regards,
SaraYes thanks. Using it since today.
ReplyI’ve just looked at the tutorial for ESP8266 and see the snipped is exactly the same: Put after this line:
Serial.println(WiFi.localIP());
//The ESP8266 tries to reconnect automatically when the connection is lost
WiFi.setAutoReconnect(true);
WiFi.persistent(true);Is this correct ?
Reply
Perfect ,this is exactly what I was looking for to improve my project.
Reply
Like always, it’s really well explained.
Thank youImportantísma información.
ReplyTodos estos posts serán clásicos de la literatura técnica.
ReplyGreat advice. Could be the solution to my remote weather station losing connection after a power cut.
Reply
Does the code work with a Wemos device??Do you have information about this functionality to add to esp32 with python?
ReplyLiving close to an airport, my router occasionally disconnects the 5 GHz band for one minute due to RADAR priority, resetting the whole WiFi. Your tutorial shows how to handle this.
Reply
Thank you!Great Job Rui and Sara,
you are doing a great Job, this website is the first place I check when I am stuck with some thing, your tutorials helped me a lot with my projects,
Thanks a lot for all the efforts, keep the good work coming
Thanks
Replyhi sara im facing a problem with wifi reconnecting after a deep sleep mode . the first 1-2hrs it gave me the reading but not same time after it wake up but thats fine im ok but the problem here is after 2 hrs it just reconnecting only not connected ….
ReplyHello Sara,
I have a slightly different issue with wifi and esp32. I have a project with the esp32 where it connects itself to my wifi. After uploading the code everything works perfectly. I can turn on and off the board with a switch and it will always work. The next day when i turn on the device again it cant connect to my local network. No matter how many times i turn on/off it wont work. I have to reboot my wifi repeater in order for the board to find the wifi network again. Have you already faced a similar issue?
ReplyHello,
This behaviour of ESP modules is often observed. They try to connect after power cycling to a router (Asus, Unifi, Netgear, etc.) that is configured as a DHCP server but get no connection until the router is rebooted.
Sometimes the solution is to assign a static IP to the ESP module (e.g. 192.168.1.xx) but then linked to the module itself (“hardware” programmed into the module) because an IP reservation (linked to MAC address in the router’s firmware) seems to achieve the same thing, is easy to realise but remains DHCP and therefore does not work.
Greetings
ReplyHello Roland,
I have followed your advice regarding assigning a static IP to the ESP, however this was unsuccesful. What i did find out is the following:
Im using a Fritz Repeater. When the esp32 is working correctly with wifi the funkchannel in the repeater is channel 1. When the esp32 stops working i have checked the channel in the repeater has automatically changed to channel 11.
In order to solve this issue one should configure the repeater not to change channels automatically. I have read in some forum the ESP’s work ideally with channels < 10.I still havent changed the channel but I have come one step closer to the solution.
thanks for your help
Reply
A Wemos use the ESP8266 no ?
Reply
https://randomnerdtutorials.com/solved-reconnect-esp8266-nodemcu-to-wifi/Like
ReplyGetting error in following lines
WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);
no matching function for call to ‘WiFiClass::onEvent(void (&)(arduino_event_id_t, arduino_event_info_t), system_event_id_t)’
In function ‘void WiFiStationDisconnected(arduino_event_id_t, arduino_event_info_t)’:
Reply
CameraWebServerBluFi:30:23: error: ‘union arduino_event_info_t’ has no member named ‘disconnected’; did you mean ‘eth_connected’?
Serial.println(info.disconnected.reason);
^~~~~~~~~~~~
eth_connectedGetting the WIFI to work reliability is a problem. I have 20 plus esp32’s that I want to deploy to weight, check temperature and humidity on bee hives. I have explained this in other comments. I use a filemanager.h to allow the attachment to a SSID with Password. This works fine and the units get on line OK and attach to an AP point in the field. This runs back to my house via ethernet cable and the 115vac cable from the house. I poll the units every 5min via a Raspberry Pi in to spread sheets (WT, TEMP, HMD;IP). This works great once running (I may have to cycle power to get some units to get on line). The main problem is a power outage at my home when everything goes down. When the power is restored, the esp32’s come back faster than the router and AP’s. I tried to hold up the request to get back on line via a random time Delay in the esp32’s from 30 to 60 sec(30000-60000). It wasn’t long enough(need several mins for network to stabilize. By that time the esp32 hove default to the factory IP 192.168.4.1, and I would have to go to field to use the browser interface on say an Iphone. Setting the delay time in the esp32’s longer is not a good option. If I am redoing SW and uploading I got to wait to see the results on the PC screen. My solution right now is to install a Time Delay After Energization (TDAE) relay. I will provide power to the esp32’s say 10mins after power is restored as the router and AP’s get on line in ~2-3min. Most of the time, when I unplug a esp32, move it and power it on; it comes back up and attaches ok. I also will use a wifi power plug after restart to be able to cycle power via of an APP if some units don’t come back on line. I have yet to get this “cobbled” together to fully check this out. I intend to split the esp32’s in to groups of say 4 to trying to get a restart of all units and not drop another unit. The only other way is this maybe to use a “hard” SSID and PW. Hate to have “20plus unloads” to handle. I am still keeping the random delay timer from 5 to 30 sec so all units are not trying to get on the AP’s at the same time and several TDAE’s set at different times.
ReplyYou have a typo in:
Reply
Serial.print(“RRSI: “);
I think it should be:
Serial.print(“RSSI: “);Had an error like this:
Wlan.cpp:32:64: error: no matching function for call to ‘WiFiClass::onEvent(void (&)(arduino_event_id_t, arduino_event_info_t), system_event_id_t)’
WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);Had to change the events to start with ‘ARDUINO_EVENT_WIFI_STA_’
So ‘SYSTEM_EVENT_STA_CONNECTED’ became ‘ARDUINO_EVENT_WIFI_STA_CONNECTED’
ReplyI have ESP wifi connect to my Router and able transfer data just between tcp connection fine. I power off (disconnect wifi) the router but I don’t get the SYSTEM_EVENT_STA_DISCONNECTED event. Please explain.
ReplyHello Sara,
I would like to contact you.
How could I find you on Linkedin?https://www.linkedin.com/in/bhishmahernandez/
ReplyBecause I was already using a RemoteMillis delay in my script, I changed the variable “interval” (see below) so that they would not conflict. I think this is correct?
unsigned long interval = 2000; // Press the remote for at least 2 seconds
Reply
unsigned long lastRemoteMillis;
unsigned long previousMillis = 0;
unsigned long intervalw = 30000; // Period between checks for Wifi connections eg 30secHello Sara, I have a problem, I recently changed my esp32 for another, everything is cool, the wifi drops and reconnects, but if it is starting the esp it stays in a loop like this:
rst:0x1 (POWERON_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:1216
ho 0 tail 12 room 4
load:0x40078000,len:10944
load:0x40080400,len:6388
entry 0x400806b4
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..And the only way is to restart it by the physical button. I have the fixed IP on the router, it does it sometimes, not always… And with the old esp32 it didn’t do it, I’m wondering what could it be?
The only difference between the ESp32 is that the old one only connected and uploaded code, the new one I have to press the physical boot button, I don’t know if it has something to do with it.
ReplyI answer myself.
Modify part of your code (googling):
WiFi.begin(ssid, password);
Serial.print(“Connecting to WiFi ..”);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(‘.’);
delay(1000);And so I stay:
uint32_t notConnectedCounter = 0;
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println(“Conectando al WiFi..”);
notConnectedCounter++;
if(notConnectedCounter > 150) { // Reset board if not connected after 5s
Serial.println(“Reseteando por que no conecta el WiFi.”);
ESP.restart();
}So far I have no problems, everything is ok, I will continue testing.
Reply
Hello
I have an esp32 that has a 4 pin rgb led connected to the board. How would I write the code for an event so that if it disconnects from the WiFi it will blink the yellow led until it reconnects to the WiFi? Can I have it do both where it is blinking until it connects again then once it connects again it stops blinking?
I’m new to all this so any help is great as to how to write this.
ReplyHi.
Reply
It might help to take a look at Wi-Fi events:https://randomnerdtutorials.com/esp32-useful-wi-fi-functions-arduino/#10
Regards,
SarHello
The link is for the WiFi manager functions. That I already have. I am trying to have my light blink when it loses internet and stop blinking when it reconnects. But I’m not sure how to have it blink or how to have it reconnect if it disconnects instead of going to the wifimanager page
Reply
Hi Everyone,
I have a problem with the raw sketch, When I try and compile it in the Arduino IDE or
In vscode it will not compile. It gives me the following error:src\main.cpp: In function ‘void WiFiStationDisconnected(system_event_id_t, system_event_info_t)’:
src\main.cpp:29:23: error: ‘union system_event_info_t’ has no member named ‘wifi_sta_disconnected’ Serial.println(info.wifi_sta_disconnected.reason);
^
In file included from C:\Users\lfree.platformio\packages\framework-arduinoespressif32\libraries\WiFi\src/WiFi.h:31:0,
from src\main.cpp:11:
src\main.cpp: In function ‘void setup()’:
C:\Users\lfree.platformio\packages\framework-arduinoespressif32\libraries\WiFi\src/WiFiType.h:35:22: error: ‘ARDUINO_EVENT_WIFI_STA_CONNECTED’ is not a member of ‘system_event_id_t’
#define WiFiEvent_t system_event_id_t
^
src\main.cpp:42:38: note: in expansion of macro ‘WiFiEvent_t’
WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
^
C:\Users\lfree.platformio\packages\framework-arduinoespressif32\libraries\WiFi\src/WiFiType.h:35:22: error: ‘ARDUINO_EVENT_WIFI_STA_GOT_IP’ is not a member of ‘system_event_id_t’
#define WiFiEvent_t system_event_id_t
^
src\main.cpp:43:27: note: in expansion of macro ‘WiFiEvent_t’
WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
^
C:\Users\lfree.platformio\packages\framework-arduinoespressif32\libraries\WiFi\src/WiFiType.h:35:22: error: ‘ARDUINO_EVENT_WIFI_STA_DISCONNECTED’ is not a member of ‘system_event_id_t’
#define WiFiEvent_t system_event_id_t
^
src\main.cpp:44:41: note: in expansion of macro ‘WiFiEvent_t’
WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
^
*** [.pio\build\esp32doit-devkit-v1\src\main.cpp.o] Error 1
=================================== [FAILED] Took 3.26 seconds ===================================I have tried everything I can think of, but no luck. I hope someone can help
Thank you.Larry
ReplyI finally solved the issue with not compiling on the arduino.ide. I deleted the arduino.ide and reinstalled it. The sketch worked without any issues. I still cannot get it to compile on vscode/platformio. I will continue to try and solve that problem. I think it may have something to do with the way the functions are not declared in the sketch.
Larry
Reply
Hi,
Reply
I am using WiFiManager.h on an ESP32.
Would the sketch ( WiFi.disconnect(); WiFi.reconnect(); ) also work to reconnect, or is there any other way to reconnect ? I tried using wm.setWifiAutoreconnect (true) but this seems not to work.
Thanks.Both codes work. But after compiling, loading and resetting, my ESP connects to wifi only if I simply change the board to arduino IDE 2.board is ESP-WROOM32.Ai idea why this happens?
ReplySpecifically, only if I select the Arduino Uno board.
ReplyHi Sara
Reply
Thank you very much for your useful teachings.
You were directed to this tutorial for the Firebase timeout error.
I applied the Wifireconnect plugin, but I still get the timeout error.
Is there a way to try again when I get a timeout error in Firebase?
ThanksHello
Reply
I switched to FirebaseClient. I think I’ll be able to use error checking.
if (aResult.isError()) {
Firebase.printf(“Error task: %s, msg: %s, code: %d\n”, aResult.uid().c_str(), aResult.error().message().c_str(), aResult. error().code());
Serial.println(“Error received!!!!!!”);
delay(10000);
//ESP.restart();
//WiFi.reconnect();
//FirebaseApp.getRefreshToken();
}Hello everyone,
I’m facing a WiFi reconnection issue with my ESP32-WROOM board.
Reply
When my ESP32 goes out of range of the WiFi router, it correctly detects the disconnection. However, when I bring it back into the WiFi range, it does not reconnect automatically, even though my reconnection logic is running in the loop.









