NTPClient demo using ESP8266 driver library built in function. Original code from Jack Berkhout that works very fast, may depend on users connection, however I get the time back and RTC set within 200mS.
Dependencies: mbed ESP8266-OS2
main.cpp
00001 #include "mbed.h" 00002 #include "ESP8266.h" 00003 00004 Serial pc(USBTX,USBRX); 00005 ESP8266 esp(D10,D2,0); // tx, rx, debug (STM32F401RE) 00006 DigitalOut led(LED1); 00007 00008 char ssid[32] = "ssid"; // enter your router ssid inside the quotes 00009 char pwd [32] = "pwd"; // enter your router password inside the quotes 00010 int Seconds; 00011 char timebuf[60]; 00012 struct tm t; 00013 00014 Timer t1; 00015 00016 int main() { 00017 00018 pc.baud(460800); //set a fast terminal (9600 Mbed default) 00019 00020 pc.printf("\033[0m\033[2J\033[H\n ----- NTP Client to set RTC -----\r\n\n\n"); 00021 pc.printf("----- NTP can take up to 30 Seconds to aquire -----\r\n\n\n"); 00022 pc.printf("Initialise!\r\n\n"); 00023 pc.printf("ESP8266 Firmware:\r\n%s\r\n\n", esp.getFirmware()); 00024 time_t seconds = time(NULL); 00025 strftime(timebuf,100,"Initial RTC Time= %H:%M:%S Date= %a %d %b %Y", localtime(&seconds)); 00026 pc.printf("\r\n%s\r\n\n\n",timebuf); 00027 pc.printf("Checking if AUTOCONNECT with last settings\r\n\n"); 00028 wait(2); // allow time for ESP to autoconnect 00029 esp.startup(3); 00030 00031 while(1){ 00032 00033 if(!esp.isConnected()){ 00034 printf("AUTOCONNECT failed\r\n\n"); 00035 printf("Connecting to AP ssid: %s, pwd: %s\r\n",ssid,pwd); 00036 esp.connect(ssid, pwd); 00037 } 00038 pc.printf("Connected\r\n\n"); 00039 pc.printf("Wi-Fi IP - %s\r\n", esp._STAIP_buffer); 00040 pc.printf("Wi-Fi RSSI: %d\r\n\n", esp.getRSSI()); 00041 pc.printf("Get NTP time...\r\n\n\n"); 00042 t1.reset();t1.start(); 00043 Seconds = esp.getNTP("1.nl.pool.ntp.org",3600,1); 00044 t1.stop(); 00045 if (Seconds>0){ 00046 pc.printf("\033[1;36m Seconds since 1970: %d\r\n\n", Seconds); 00047 pc.printf("\033[0m NTP response... %f Seconds\r\n\n\n",t1.read()); 00048 } 00049 else {pc.printf("\033[1;36m Error\r\n\n");} 00050 00051 pc.printf(" Time: Date:\r\n"); 00052 pc.printf("\033[1;32m\r\n"); 00053 for (unsigned i = 0; i < 10; i++) { 00054 time_t t = time(NULL); 00055 strftime(timebuf,100," %H:%M:%S %a %d %b %Y", localtime(&t)); 00056 pc.printf("\033[2K\033[1A%s\r\n",timebuf); 00057 while(t==time(NULL)){led=!led;wait(.1);} 00058 } 00059 pc.printf("\033[0m\033[2J\033[H\n\nRestart every 10 seconds\r\n\n"); 00060 } 00061 }
Generated on Mon Aug 15 2022 15:09:03 by 1.7.2