Hello!
I’m fine-tuning my NTP digital clock device. I’m using an ESP32, a RTC module with coin battery, and a 4-digit 7 segment display. It’s a simple thing, it would probably cost $3 at a goodwill.
Except I have mine connect with an NTP server at 0201 to sync with the time, hopefully to fix the Daylight savings hour change. And the battery RTC module lets the clock get unplugged and retains the time despite power loss.
My latest code, I’ve found, sometimes freezes the clock at 0201. I noticed that it’s in an infinite while loop, attempting to connect to the wifi. (That’s my hunch.) I’m introducing a function that will allow only a certain number of wifi connection attempts before giving up.
My function code is:
void ntpClockCheck(){ Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { for (int tries = 0; tries <= 5; tries++){ delay(500); Serial.print("."); } } Serial.println("Updating with NTP"); Serial.println(""); Serial.println("WiFi connected."); // Init and get the time configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); //disconnect WiFi as it's no longer needed WiFi.disconnect(true); WiFi.mode(WIFI_OFF); }
Like I said, maybe one night out of the week, I’ll wake up to see the time display frozen at 2:01. Is my function code written correctly, giving it 5 attempts to connect?
Do I need to introduce a
break
somewhere?
Thank you
Don
What you have there is probably not what you want to do. You are saying that if the WiFi is not connected try to connect 6 times; Then if the WiFi is not connected try to connect 6 times; Then if the WiFi is not connected try to connect 6 times; ad nauseam. Note your loop goes from 0 to 5 which is 6 times.
What you probably want is to get rid of the while loop altogether. Then just do an if WiFi is not connected then try to connect 5 times. At the end of that check if WiFi is still not connected and do an ESP.restart().
Thank you Steve. I wouldn’t have spotted the while loop issue. I think I’ll change the NTP check time and troubleshoot it during the daytime. Maybe I can add a little LED that indicates a WiFi connection failure.
Love the esp.restart() idea.
Thank you Steve. I wouldn’t have spotted the while loop issue. I think I’ll change the NTP check time and troubleshoot it during the daytime. Maybe I can add a little LED that indicates a WiFi connection failure.
Love the esp.restart() idea.
Hi Donald.
You can also add a Wi-Fi event that detects when Wi-Fi is not connected and try to connect or restart when that happens.
It’s everything explained here: https://randomnerdtutorials.com/solved-reconnect-esp32-to-wifi/
Scroll down to the “Wi-Fi Events” section.
Regards,
Sara