ESP32 NTP-Client-Minimalbeispiel mit NTPClient_Generic und PlatformIO
English
Deutsch
Beispiel für die Verwendung von NTPClient_Generic
main.cpp
main.cpp
#include <Arduino.h>
#include <WiFi.h>
#include <NTPClient_Generic.h>
#define TIME_ZONE_OFFSET_HRS 1 // UTC+1 für Deutschland, Winterzeit
#define NTP_UPDATE_INTERVAL_MS 60000L // Alle 60s automatisch aktualisieren
WiFiUDP ntpUDP;
NTPClient ntpClient(ntpUDP, "europe.pool.ntp.org", (3600 * TIME_ZONE_OFFSET_HRS), NTP_UPDATE_INTERVAL_MS);
void ntpUpdateTask(void* param) {
while(true) {
// NTP aktualisieren. Dies wird nur TATSÄCHLICH aktualisiert, wenn
// der NTP-Client seit NTP_UPDATE_INTERVAL_MS nicht aktualisiert wurde
ntpClient.update();
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void setup() {
Serial.begin(115200);
// WLAN erzwungen zurücksetzen, um Verbindungsfehler zu vermeiden
WiFi.disconnect(true);
// Hostnamen setzen
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname("ESP-NTP");
// Mit WLAN verbinden
WiFi.begin("MyWifiSSID", "MyWifiPassword");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Wifi connecting...");
}
// NTP-Client starten (d.h. auf NTP-Pakete lauschen)
ntpClient.begin();
// Task erstellen, um NTP automatisch im Hintergrund zu aktualisieren
xTaskCreate(ntpUpdateTask, "NTP update", 2000, nullptr, 1, nullptr);
}
void loop() {
delay(1000);
if (ntpClient.updated()) {
Serial.println("# Time in sync with NTP server");
} else {
Serial.println("# TIME NOT IN SYNC WITH NTP SERVER !");
return; // Zeit nicht ausgeben
}
Serial.println("UTC : " + ntpClient.getFormattedUTCTime());
Serial.println("UTC : " + ntpClient.getFormattedUTCDateTime());
Serial.println("LOC : " + ntpClient.getFormattedTime());
}platformio.ini
platformio.ini
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
khoih.prog/NTPClient_Generic @ ^3.2.2
TimeBeispielausgabe:
example_output.txt
Wifi connecting...
Wifi connecting...
Wifi connecting...
# TIME NOT IN SYNC WITH NTP SERVER !
# Time in sync with NTP server
UTC : 01:22:07
UTC : 01:22:07 Sun 07 Feb 2021
LOC : 02:22:07
# Time in sync with NTP server
UTC : 01:22:08
UTC : 01:22:08 Sun 07 Feb 2021
LOC : 02:22:08
# Time in sync with NTP server
UTC : 01:22:09
UTC : 01:22:09 Sun 07 Feb 2021
LOC : 02:22:09Check out similar posts by category:
C/C++, ESP8266/ESP32, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow