![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Backing up an unused program in case of future need
time.cpp
- Committer:
- andrewboyson
- Date:
- 2016-06-02
- Revision:
- 7:024ace6d943c
- Parent:
- 6:be97d38e0b01
- Child:
- 8:45a0205a298f
File content as of revision 7:024ace6d943c:
#include "mbed.h" #define ONE_MILLION 1000000 static Ticker ticker; static volatile uint64_t unixTime16ths; static void tick(void) { unixTime16ths++; } void TimeSet(uint32_t t) { unixTime16ths = (uint64_t)t << 4; } uint32_t TimeGet() { return unixTime16ths >> 4; } void TimeSet16ths(uint64_t t) { unixTime16ths = t; } uint64_t TimeGet16ths() { return unixTime16ths; } void TimeToTm(uint32_t time, struct tm* ptm) { int seconds = time % 60; time /= 60; int minutes = time % 60; time /= 60; int hours = time % 24; time /= 24; int daysLeft = time; //Add a year at a time while there is more than a year of days left int year = 1970; //Unix epoch is 1970 int dayOfWeek = 4; //1 Jan 1970 is a Thursday int dayOfYear; int leapYear; while(1) { //See if it is a leap year int year4 = !(year % 4); int year100 = !(year % 100); int year400 = !(year % 400); leapYear = false; if (year4) leapYear = true; if (year100) leapYear = false; if (year400) leapYear = true; //Find the number of days in this year int daysInYear = leapYear ? 366 : 365; //Stop if this is the final year if (daysLeft < daysInYear) break; //Calculate the current day of the week at the start of the year dayOfWeek += leapYear ? 2 : 1; if (dayOfWeek >= 7) dayOfWeek -= 7; //Move on to the next year daysLeft -= daysInYear; year++; } dayOfYear = daysLeft; dayOfWeek += daysLeft; dayOfWeek %= 7; //Add a month at a time while there is more than a month of days left int month = 0; while(1) { int daysInMonth; switch (month + 1) { case 1: daysInMonth = 31; break; case 2: daysInMonth = leapYear ? 29 : 28; break; case 3: daysInMonth = 31; break; case 4: daysInMonth = 30; break; case 5: daysInMonth = 31; break; case 6: daysInMonth = 30; break; case 7: daysInMonth = 31; break; case 8: daysInMonth = 31; break; case 9: daysInMonth = 30; break; case 10: daysInMonth = 31; break; case 11: daysInMonth = 30; break; case 12: daysInMonth = 31; break; } //Stop if this is the last month if (daysLeft < daysInMonth) break; //Move onto next month daysLeft -= daysInMonth; month++; } ptm->tm_sec = seconds; ptm->tm_min = minutes; ptm->tm_hour = hours; ptm->tm_mday = daysLeft + 1; ptm->tm_mon = month; ptm->tm_year = year - 1900; ptm->tm_wday = dayOfWeek; ptm->tm_yday = dayOfYear; } void TimeGetTm(struct tm* ptm) { uint32_t time = TimeGet(); TimeToTm(time, ptm); } static Timer timer; int TimeScanUs = 0; int TimeMain() { int scanUs = timer.read_us(); timer.reset(); timer.start(); if (scanUs > TimeScanUs) TimeScanUs++; if (scanUs < TimeScanUs) TimeScanUs--; return 0; } int TimeInit() { ticker.attach_us(&tick, ONE_MILLION >> 4); timer.stop(); timer.reset(); return 0; }