|
NTP time serverInternet time servers offer time services for several hundred million systems worldwide. They use a standardized data format, the Network Time Protocol (NTP). The LinkUp's ESP32 uses a library that implements the NTP. With the import of the small module ntptime the functions getTimeRaw() and getTime() are available to the micro:bit programmer, which return the current date time as tuple or in string format. In the following example the ESP32 logs on to an access point, retrieves the time information about every 10 seconds in raw format from the standard server pool.ntp.org (or from ch.pool.ntp.org). The function getTime() returns the date time information as colon separated fields in a char array. In order to split it, the well-known strtok() algorithm is used. #include <linkup.h> #include <string.h> void setup() { Serial.begin(9600); Wire.begin(); char reply[128]; Serial.println("Connecting..."); connectAP("myssid", "mypassword", reply); } void loop() { char reply[128]; getNtpTimeRaw("", reply); // getNtpTimeRaw("ch.pool.ntp.org", reply); Serial.println(reply); char* p = strtok(reply, ":"); Serial.println("yyyy, mm, dd, h, m, s, weekday, dayofyear (GMT)"); while (p != NULL) { Serial.println(p); p = strtok(NULL, ":"); } delay(10000); } A typical outout in the console window is: 2019:9:9:14:53:45:2:252 // NtpTime2.ino #include <linkup.h> #include <TimeLib.h> #include <ntptime.h> void setup() { Serial.begin(9600); Wire.begin(); char reply[128]; Serial.println("Connecting..."); connectAP("myssid", "mypassword", reply); } void loop() { time_t t = getNtpTime("pool.ntp.org"); char date[64]; sprintf(date, "%d.%d.%d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t)); Serial.println(date); delay(10000); } The module ntptime also supports the setSyncProvider() function pointer registration, as seen in the following example: // NtpTime3.ino
// NtpTime4.ino #include <linkup.h> #include <TimeLib.h> #include <ntptime.h> #include <TM1637Display.h> #define CLK 2 #define DIO 3 TM1637Display display(CLK, DIO); void clear() { uint8_t data[4] = {0, 0, 0, 0}; display.setSegments(data); } void setup() { Wire.begin(); display.setColon(true); display.setBrightness(0x0f); char reply[128]; connectAP("raspilink", "aabbaabbaabb", reply); setSyncProvider(getNtpTime); } void loop() { time_t t = now(); int mez = hour(t) + 1; // MEZ summer time int time = mez * 100 + minute(t); clear(); display.showNumberDec(time, false, 4, 0); delay(10000); } Further examples will follow.
|
||