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

Committer:
star297
Date:
2019-02-14
Revision:
1:b7cce2519e5e
Parent:
0:c284c33c96f1

File content as of revision 1:b7cce2519e5e:

#include "mbed.h"
#include "ESP8266.h"

Serial pc(USBTX,USBRX);
ESP8266 esp(D10,D2,0);    // tx, rx, debug (STM32F401RE)
DigitalOut led(LED1);

char ssid[32] = "ssid";   // enter your router ssid inside the quotes
char pwd [32] = "pwd"; // enter your router password inside the quotes
int Seconds;
char timebuf[60];
struct tm t; 

Timer t1;

int main() {

    pc.baud(460800); //set a fast terminal (9600 Mbed default)
    
    pc.printf("\033[0m\033[2J\033[H\n        ----- NTP Client to set RTC -----\r\n\n\n");
    pc.printf("----- NTP can take up to 30 Seconds to aquire -----\r\n\n\n");    
    pc.printf("Initialise!\r\n\n");    
    pc.printf("ESP8266 Firmware:\r\n%s\r\n\n", esp.getFirmware());   
    time_t seconds = time(NULL);
    strftime(timebuf,100,"Initial RTC Time= %H:%M:%S Date= %a %d %b %Y", localtime(&seconds)); 
    pc.printf("\r\n%s\r\n\n\n",timebuf);    
    pc.printf("Checking if AUTOCONNECT with last settings\r\n\n");    
    wait(2);   // allow time for ESP to autoconnect 
    esp.startup(3);
    
    while(1){ 
  
        if(!esp.isConnected()){
            printf("AUTOCONNECT failed\r\n\n");
            printf("Connecting to AP ssid: %s, pwd: %s\r\n",ssid,pwd);
            esp.connect(ssid, pwd);         
        }
        pc.printf("Connected\r\n\n");
        pc.printf("Wi-Fi IP  -  %s\r\n", esp._STAIP_buffer);
        pc.printf("Wi-Fi RSSI: %d\r\n\n", esp.getRSSI());        
        pc.printf("Get NTP time...\r\n\n\n");
        t1.reset();t1.start();
        Seconds = esp.getNTP("1.nl.pool.ntp.org",3600,1);           
        t1.stop();
        if (Seconds>0){
            pc.printf("\033[1;36m   Seconds since 1970: %d\r\n\n", Seconds);
            pc.printf("\033[0m  NTP response... %f Seconds\r\n\n\n",t1.read());
        }
            else {pc.printf("\033[1;36m   Error\r\n\n");} 
        
        pc.printf("    Time:        Date:\r\n");
        pc.printf("\033[1;32m\r\n");
        for (unsigned i = 0; i < 10; i++) {        
            time_t t = time(NULL);        
            strftime(timebuf,100,"    %H:%M:%S     %a %d %b %Y", localtime(&t));         
            pc.printf("\033[2K\033[1A%s\r\n",timebuf);               
            while(t==time(NULL)){led=!led;wait(.1);} 
        }
        pc.printf("\033[0m\033[2J\033[H\n\nRestart every 10 seconds\r\n\n");
    } 
}