MBED clock sync using NTP Server from from internet

Dependencies:   EthernetInterface NTPClient mbed-rtos mbed

Fork of MbedClock by Andrew Duda

main.cpp

Committer:
ismaia
Date:
2016-02-11
Revision:
11:4d4334d909d3
Parent:
10:d9ed3d95e5eb
Child:
12:bcced6833b8f

File content as of revision 11:4d4334d909d3:

#include "mbed.h"
#include "rtos.h"
#include "EthernetInterface.h"
#include "NTPClient.h"
#include <string>


EthernetInterface   eth;
TCPSocketConnection server;
NTPClient           ntp;
DigitalOut          led1(LED1);
DigitalOut          led2(LED2);
time_t              ctTime;
 
 
void thread_func1(void const *args) {
    while (1) {
        led1 = !led1;
        Thread::wait(1000);
    }
}

void thread_func2(void const *args) {
    while (1) {
        led2 = !led2;
        Thread::wait(500);
    }
}

int main() {
    printf("Setting up ethernet interface...\r\n");
    if (eth.init() == 0 ) { //Use DHCP
       printf("Ethernet setup OK\r\n");
    }else {
       printf("Error: cannot set ethernet interface\r\n");
       return 1;
    }
    
    printf("Trying to connect...\r\n");
    wait(0.5);
    if ( eth.connect(30000) == 0 ){ 
       printf("IP Address is %s\n", eth.getIPAddress());
    }else {
       printf("Error: cannot set ethernet interface\r\n");
       return 1;
    }    
           
    printf("Trying to update time...\r\n");
    if (ntp.setTime("0.fr.pool.ntp.org") == 0)
    {
      printf("Set time successfully\r\n");      
    }
    else
    {
      printf("Error: Cannot set time\r\n");
    } 
    eth.disconnect();  
    ctTime = time(NULL);
    
    Thread thread1(thread_func1);
    Thread thread2(thread_func2);
    
    while(1) {
         printf("Current time is: %s\r\n", ctime(&ctTime));
         wait(1);
    }
}