Thumbnail for video 'Programming ESP32 with Arduino - Keep WiFi Connection Alive with a FreeRTOS Task'

← Back to courses

Keep WiFi Connection Alive with a FreeRTOS Task

Does your ESP32 need a constant WiFi connection? Use a FreeRTOS task to constantly check your connection, and re-establish it when needed.

This code has been super robust for me. I've been using it for my Home Energy Monitor, and it has been running reliably for years.

I also have a dedicated blog post about this technique.

Full code

#define WIFI_NETWORK "--- your WiFi network name ---"
#define WIFI_PASSWORD "--- your WiFi password ---"
#define WIFI_TIMEOUT_MS 20000 // 20 second WiFi connection timeout

void keepWiFiAlive(void * parameter){
if(WiFi.status() == WL_CONNECTED){
Serial.println("WiFI still connected.");
vTaskDelay(10000 / portTICK_PERIOD_MS);

Serial.println("WiFi Connecting");

unsigned long startAttemptTime = millis();

// Keep looping while we're not connected and haven't reached the timeout
while (WiFi.status() != WL_CONNECTED &&
millis() - startAttemptTime < WIFI_TIMEOUT_MS){}

// When we couldn't make a WiFi connection (or the timeout expired)
// sleep for a while and then retry.
if(WiFi.status() != WL_CONNECTED){
Serial.println("[WIFI] FAILED");

Serial.println("[WIFI] Connected: " + WiFi.localIP());

Useful resources