Simple code for comunication via TCP between the mbed and PC.
Dependencies: EthernetInterface SimpleSocket mbed-rtos mbed
Fork of SimpleSocketExamples by
Diff: examples/ntpclient.cpp
- Revision:
- 0:6dc3cfd058c6
diff -r 000000000000 -r 6dc3cfd058c6 examples/ntpclient.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/ntpclient.cpp Mon Feb 04 09:29:18 2013 +0000 @@ -0,0 +1,31 @@ +#include "SimpleSocket.h" + +void ntpclient() { + char *NTP_SERVER = "pool.ntp.org"; + printf("ntp server = %s\n", NTP_SERVER); + + while (true) { + DatagramSocket datagram; + char buf[48] = {0x23}; // 00100011 LI(0), Version(4), Mode(3: Client) + datagram.write(buf, sizeof(buf)); + datagram.send(NTP_SERVER, 123); + + //datagram.setTimeout(5.0); + if (datagram.receive() > 0) { + if (datagram.read(buf, sizeof(buf)) > 0) { + unsigned long seconds = 0; + for (int i = 40; i <= 43; i++) + seconds = (seconds << 8) | buf[i]; + set_time(time_t(seconds - 2208988800ULL)); + char timestamp[16]; + time_t jstime = time(NULL) + 9 * 3600; + strftime(timestamp, sizeof(timestamp), "%m/%d %X", localtime(&jstime)); + printf("Time: %s\n", timestamp); + break; + } + } else { + printf("no answer\n"); + wait(1.0); + } + } +} \ No newline at end of file