I'm using an ESP32 (also applies to ESP8266) in a project that needs to maintain a stable Wi-Fi connection. Occasionally, the Wi-Fi connection drops—due to signal issues or router resets—and the device doesn't reconnect automatically unless I manually reboot it.
I want to know how to automatically detect a dropped Wi-Fi connection and reconnect to it programmatically, without having to reset the entire board.
This is a very common issue with ESP boards, as a dropped connection won't automatically trigger a new connection attempt unless the logic is specifically handled in your code. The most reliable and efficient way to solve this is by using a Wi-Fi event handler.
This approach is superior to periodically checking the connection status because it's event-driven. Your code will react immediately to a disconnection event, rather than waiting for a specific time interval to check if the Wi-Fi is still connected.
The event-driven method is more efficient because your code reacts instantly when the ESP disconnects, instead of waiting for a timer to notice the problem. For example, on the ESP32 you can use:
#include <WiFi.h>
void WiFiEvent(WiFiEvent_t event) {
switch (event) {
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi disconnected! Reconnecting...");
WiFi.reconnect();
break;
case SYSTEM_EVENT_STA_CONNECTED:
Serial.println("WiFi connected!");
break;
}
}
void setup() {
Serial.begin(115200);
WiFi.onEvent(WiFiEvent);
WiFi.begin("YourSSID", "YourPassword");
}
void loop() {
// Your main code
}
With this setup, the ESP automatically attempts to reconnect whenever the connection drops, without wasting resources on continuous polling.