Simply Clock
Dependencies: EthernetNetIf NTPClient_NetServices TextLCD mbed
Diff: main.cpp
- Revision:
- 0:7e901efc73e7
- Child:
- 1:7974d199ed39
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Mar 25 16:54:13 2011 +0000 @@ -0,0 +1,99 @@ +#include "mbed.h" +#include "time.h" +#include "TextLCD.h" +#include "EthernetNetIf.h" +#include "NTPClient.h" + +#define TIMEZONE (9 * 60 * 60) + +TextLCD lcd(p21, p22, p23, p24, p25, p26); + +EthernetNetIf eth; +NTPClient ntp; + +unsigned long convert_gregorian_to_julian(int year, int month, int day) +{ + if (month < 3) { + month += 9; + year--; + } else { + month -= 3; + } + year += 4800; + int c = year / 100; + return c * 146097 / 4 + (year - c * 100) * 1461 / 4 + (153 * month + 2) / 5 + day - 32045; +} + +void convert_julian_to_gregorian(unsigned long j, int *year, int *month, int *day) +{ + int y, m, d; + y = (j * 4 + 128179) / 146097; + d = (j * 4 - y * 146097 + 128179) / 4 * 4 + 3; + j = d / 1461; + d = (d - j * 1461) / 4 * 5 + 2; + m = d / 153; + d = (d - m * 153) / 5 + 1; + y = (y - 48) * 100 + j; + if (m < 10) { + m += 3; + } else { + m -= 9; + y++; + } + *year = y; + *month = m; + *day = d; +} + +void display(int year, int month, int day, int hour, int minute, int second) +{ + lcd.cls(); + lcd.printf("%04u-%02u-%02u\n", year, month, day); + lcd.printf("%02u:%02u:%02u\n", hour, minute, second); +} + +int main() +{ + eth.setup(); + + Host server(IpAddr(), 123, "ntp.jst.mfeed.ad.jp"); + + bool adjust = true; + + double last = 0; + + while (1) { + if (adjust) { + ntp.setTime(server); + adjust = false; + } + + time_t t = time(0); + double s = t + 2440588.0 * 24 * 60 * 60; // chronological julian second + + if (s > last) { + last = s; + + s += TIMEZONE; + + unsigned long cjd = (unsigned long)(s / (24 * 60 * 60)); // chronological julian day + int year, month, day, hour, minute, second; + convert_julian_to_gregorian(cjd, &year, &month, &day); + second = (int)fmod(s, 24 * 60 * 60); + hour = second / (60 * 60); + minute = second / 60 % 60; + second %= 60; + + display(year, month, day, hour, minute, second); + + if (hour == 4 && minute == 0 && second == 0) { + adjust = true; + } + } + + wait(0.1); + } + + return 0; +} +