ESP WiFi hung solution



  • This is how I solved the issue of ESP32 GW hanging when WiFi connection is lost or not established. It is not 100% my original work, it has been put together using bits and pieces, but it works.

    I simply use a watchdog timer:

    #include "esp_system.h" // added for WDT
    hw_timer_t* timer = NULL;
    
    // WDT related
    void IRAM_ATTR resetModule() {
    	Serial.println("reboot\n");
    	ESP.restart();
    }
    
    void WdtReset()
    {
        timerWrite(timer, 0); //reset timer (feed watchdog)
    }
    
    void StartWatchDog()
    {
        timer = timerBegin(0, 240, true); //timer 0, div 80
        timerAttachInterrupt(timer, &resetModule, true);
        timerAlarmWrite(timer, 5000000, false); //set time in us
        timerAlarmEnable(timer); //enable interrupt
    }
    
    IPAddress ConnectWiFi()
    {
        Serial.println();
        Serial.println();
        Serial.print("Connecting to ");
        Serial.println(MY_WIFI_SSID);
    
        /* Explicitly set the ESP to be a WiFi-client, otherwise, it by default,
           would try to act as both a client and an access-point and could cause
           network-issues with your other WiFi-devices on your WiFi-network. */
    #ifdef ESP32
        WiFi.persistent(false);
        WiFi.mode(WIFI_STA);
    #endif // ESP32
    
        WiFi.begin(MY_WIFI_SSID, MY_WIFI_PASSWORD);
    
    
        while (WiFi.status() != WL_CONNECTED) {
            digitalWrite(LED_BUILTIN, LED_ON);
            wait(500);
            Serial.print(".");
            digitalWrite(LED_BUILTIN, LED_OFF);
            wait(500);
        }
    
    #ifdef ESP32
        WiFi.setAutoReconnect(true);
    #endif // ESP32
    
        return WiFi.localIP();
        
    }
    void before()
    {
    
        StartWatchDog();
    
        // We start by connecting to a WiFi network
        localIP = ConnectWiFi();
        myHostname = WiFi.getHostname();
    
        WdtReset();
    
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(localIP);
        Serial.println(myHostname);
    
    // do other stuff ...
    
    }
    
    void loop()
    {
       
    
        // check WiFi connection
        if (WiFi.status() != WL_CONNECTED) return; // the WDT is not reset
        WdtReset();
    
    // do other stuff ...
    }
    

    Hope it helps


Log in to reply
 

Suggested Topics

  • 1
  • 186
  • 4
  • 7
  • 10
  • 44
  • 182
  • 5

119
Online

10.6k
Users

10.8k
Topics

111.0k
Posts