Code Monkey home page Code Monkey logo

time's Introduction

Arduino Time Library

Time is a library that provides timekeeping functionality for Arduino.

Using the Arduino Library Manager, install "Time by Michael Margolis".

The code is derived from the Playground DateTime library but is updated to provide an API that is more flexible and easier to use.

A primary goal was to enable date and time functionality that can be used with a variety of external time sources with minimum differences required in sketch logic.

Example sketches illustrate how similar sketch code can be used with: a Real Time Clock, internet NTP time service, GPS time data, and Serial time messages from a computer for time synchronization.

Functionality

To use the Time library in an Arduino sketch, include TimeLib.h.

#include <TimeLib.h>

The functions available in the library include

hour();            // the hour now  (0-23)
minute();          // the minute now (0-59)
second();          // the second now (0-59)
day();             // the day now (1-31)
weekday();         // day of the week (1-7), Sunday is day 1
month();           // the month now (1-12)
year();            // the full four digit year: (2009, 2010 etc)

there are also functions to return the hour in 12-hour format

hourFormat12();    // the hour now in 12 hour format
isAM();            // returns true if time now is AM
isPM();            // returns true if time now is PM

now();             // returns the current time as seconds since Jan 1 1970

The time and date functions can take an optional parameter for the time. This prevents errors if the time rolls over between elements. For example, if a new minute begins between getting the minute and second, the values will be inconsistent. Using the following functions eliminates this problem

time_t t = now(); // store the current time in time variable t
hour(t);          // returns the hour for the given time t
minute(t);        // returns the minute for the given time t
second(t);        // returns the second for the given time t
day(t);           // the day for the given time t
weekday(t);       // day of the week for the given time t
month(t);         // the month for the given time t
year(t);          // the year for the given time t

Functions for managing the timer services are:

setTime(t);                      // set the system time to the give time t
setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr
                                 // (2010 or 10 sets year to 2010)
adjustTime(adjustment);          // adjust system time by adding the adjustment value
timeStatus();                    // indicates if time has been set and recently synchronized
                                 // returns one of the following enumerations:
timeNotSet                       // the time has never been set, the clock started on Jan 1, 1970
timeNeedsSync                    // the time had been set but a sync attempt did not succeed
timeSet                          // the time is set and is synced

Time and Date values are not valid if the status is timeNotSet. Otherwise, values can be used but the returned time may have drifted if the status is timeNeedsSync.

setSyncProvider(getTimeFunction);  // set the external time provider
setSyncInterval(interval);         // set the number of seconds between re-sync

There are many convenience macros in the time.h file for time constants and conversion of time units.

To use the library, copy the download to the Library directory.

Examples

The Time directory contains the Time library and some example sketches illustrating how the library can be used with various time sources:

  • TimeSerial.pde shows Arduino as a clock without external hardware. It is synchronized by time messages sent over the serial port. A companion Processing sketch will automatically provide these messages if it is running and connected to the Arduino serial port.

  • TimeSerialDateStrings.pde adds day and month name strings to the sketch above. Short (3 characters) and long strings are available to print the days of the week and names of the months.

  • TimeRTC uses a DS1307 real-time clock to provide time synchronization. The basic DS1307RTC library must be downloaded and installed, in order to run this sketch.

  • TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock.

  • TimeRTCLog demonstrates how to calculate the difference between times. It is a very simple logger application that monitors events on digital pins and prints (to the serial port) the time of an event and the time period since the previous event.

  • TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service. The NTP protocol uses UDP and the UdpBytewise library is required, see: http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/

  • TimeGPS gets time from a GPS. This requires the TinyGPS library from Mikal Hart: http://arduiniana.org/libraries/TinyGPS

Differences

Differences between this code and the playground DateTime library although the Time library is based on the DateTime codebase, the API has changed. Changes in the Time library API:

  • time elements are functions returning int (they are variables in DateTime)
  • Years start from 1970
  • days of the week and months start from 1 (they start from 0 in DateTime)
  • DateStrings do not require a separate library
  • time elements can be accessed non-atomically (in DateTime they are always atomic)
  • function added to automatically sync time with external source
  • localTime and maketime parameters changed, localTime renamed to breakTime

Technical Notes

Internal system time is based on the standard Unix time_t. The value is the number of seconds since Jan 1, 1970. System time begins at zero when the sketch starts.

The internal time can be automatically synchronized at regular intervals to an external time source. This is enabled by calling the setSyncProvider(provider) function - the provider argument is the address of a function that returns the current time as a time_t. See the sketches in the examples directory for usage.

The default interval for re-syncing the time is 5 minutes but can be changed by calling the setSyncInterval(interval) method to set the number of seconds between re-sync attempts.

The Time library defines a structure for holding time elements that is a compact version of the C tm structure. All the members of the Arduino tm structure are bytes and the year is offset from 1970. Convenience macros provide conversion to and from the Arduino format.

Low-level functions to convert between system time and individual time elements are provided:

breakTime(time, &tm);  // break time_t into elements stored in tm struct
makeTime(&tm);         // return time_t from elements stored in tm struct

This DS1307RTC library provides an example of how a time provider can use the low-level functions to interface with the Time library.

time's People

Contributors

bolukan avatar ccoenen avatar chaeplin avatar danbates2 avatar halx4 avatar huyhoquang avatar ivankravets avatar karl-petter avatar majenkotech avatar mcauser avatar mmuecke avatar paulstoffregen avatar per1234 avatar pieterbl avatar roman3349 avatar sukkopera avatar venice1200 avatar zharovdv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

time's Issues

Strange problem using ESP8266 sample

Hello, I'm trying to use your sample sketch with an ESP8266 chip. However even when using your code exactly as it is I'm running on an error...

/Users/me/Documents/Arduino/ESP8266_NTP/ESP8266_NTP.ino: In function 'void setup()':
ESP8266_NTP:54: error: 'getNtpTime' was not declared in this scope
   setSyncProvider(getNtpTime);
                   ^
/Users/me/Documents/Arduino/ESP8266_NTP/ESP8266_NTP.ino: In function 'void loop()':
ESP8266_NTP:64: error: 'digitalClockDisplay' was not declared in this scope
       digitalClockDisplay();  
                           ^
/Users/me/Documents/Arduino/ESP8266_NTP/ESP8266_NTP.ino: In function 'void digitalClockDisplay()':
ESP8266_NTP:72: error: 'printDigits' was not declared in this scope
   printDigits(minute());
                       ^
/Users/me/Documents/Arduino/ESP8266_NTP/ESP8266_NTP.ino: In function 'time_t getNtpTime()':
ESP8266_NTP:102: error: 'sendNTPpacket' was not declared in this scope
   sendNTPpacket(timeServer);
                           ^
exit status 1
'getNtpTime' was not declared in this scope

Your code looks totally fine! So, it's quite strange... Compiling the original Arduino sketch (for a real Arduino controller) works fine as well... Then I changed the order of your functions (e.g. putting setup/loop) to the end. After that no compiler issue.

Any idea what is going wrong? I assume that the sketch works for you. Making it even stranger...
Or is there any flag handling function ordering?

Thanks, JC

Retry for Sync

Hi Paul,
thank you for the great Library. I'm using it with a Texas Instruments CC3200 Launchpad and Energia IDE.
I have an issue with the setSyncProvider function. I'm using an NTP SyncProvider function. In the rare cases, when the NTP server fails to deliver the correct Unix Timestamp, the function returns the value 0.
In this case I would expect that time will try to resync at least after the 300 s, the default value for SyncInterval. Unfortunatly is does not work. Further I would prefer to set a retry Interval in Cases of a sync failure. Do you have any advice for me

Tanks

wayfarerbasta

timeStatus() responding with numbers

I am getting values 0 and 2, but I was expecting:

timeNotSet Time's clock has not been set. The time & date are unknown.
timeSet Time's clock has been set.
timeNeedsSync Time's clock is set, but the sync has failed, so it may not be accurate.

Am I using it wrong?

Optimized breakTime()

Hi!

While trying to help a friend fit his program into an Uno, I looked for functions in his code or libraries that could be made smaller, and breakTime(), from the Time library, surfaced as a good candidate for size optimization. I gave it a try, and got good results, thus I am sharing my experience here, with the hope that it could be incorporated into the official library, and benefit others.

Well, actually I came out with two alternative versions, and since I do not know which one I like better, I am sharing both. ;-) First, the “iterative” version, which is very close to your original implementation, with only slightly streamlined code:

// leap year calulator expects year argument as years offset from 1970
#ifdef Y2100_COMPAT
#   define LEAP_YEAR(Y)     ((Y) % 4 == 2 && (Y) != 2100-1970)
#else
#   define LEAP_YEAR(Y)     ((Y) % 4 == 2)
#endif

#define DAYS_IN_YEAR(Y)  (365U + LEAP_YEAR(Y))

static  const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0

void breakTime(time_t time, tmElements_t &tm){
// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!

  uint8_t year;
  uint8_t month, monthLength;
  uint16_t days;

  tm.Second = time % 60;
  time /= 60; // now it is minutes
  tm.Minute = time % 60;
  time /= 60; // now it is hours
  tm.Hour = time % 24;
  time /= 24; // now it is days
  tm.Wday = ((time + 4) % 7) + 1;  // Sunday is day 1 

  year = 0;  
  days = 0;
  while((days += DAYS_IN_YEAR(year)) <= time) {
    year++;
  }
  tm.Year = year; // year is offset from 1970 

  days -= DAYS_IN_YEAR(year);
  time  -= days; // now it is days in this year, starting at 0

  for (month=0; month<12; month++) {
    monthLength = monthDays[month];
    if (month==1 && LEAP_YEAR(year)) { // february has 29 days
      monthLength++;
    }

    if (time >= monthLength) {
      time -= monthLength;
    } else {
        break;
    }
  }
  tm.Month = month + 1;  // jan is month 1  
  tm.Day = time + 1;     // day of month
}

Compared to the original, the changes seem almost cosmetic. Yet, on my build system (avr-gcc 4.8.2 as shipped with Ubuntu 14.04), this compiles 41% smaller (39% smaller with -DY2100_COMPAT).

A short comment about leap years: The chosen format for time_t covers the range Jan 1970 – Feb 2106. Within this range, leap years are those that are multiples of 4, with the sole exception of 2100. If we are willing to sacrifice the last six years of the range, then the test for leap years is trivial, and requires only two machine instructions (mask bits and compare). I added the #ifdef Y2100_COMPAT for those situations where coverage of 2100 – 2106 might be more important than code size.

Next the “arithmetic” version:

// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!
void breakTime(time_t time, tmElements_t &tm)
{
    tm.Second = time % 60;
    time /= 60; // now it is minutes
    tm.Minute = time % 60;
    time /= 60; // now it is hours
    tm.Hour = time % 24;
    time /= 24; // now it is days
    tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1

#ifdef Y2100_COMPAT
    if (time >= 47541) time++;  // Skip 29 Feb 2100
#endif

    time += 306;  // Origin switched to 1 Mar 1969
    uint8_t year = (time * 4 + 2) / 1461;
    time -= (year * (uint32_t) 1461 + 1) / 4;
    uint8_t month = (time * 5 + 2) / 153;  // Mar = 0
    time -= (month * 153 + 2) / 5;
    tm.Day = time + 1;

    // Switch the origin back to 1 Jan 1970, with Jan = 1
    if (month < 10) { month += 3; year--; }
    else month -= 9;
    tm.Month = month;
    tm.Year = year;
}

This one is somewhat larger than the previous, but I expect it to be faster, since it avoids looping over the years and months. It is based on the naive idea that you can compute the year number by dividing the time by the average length of a year (1461/4 days), and you can compute the month number by diving the time-of-year by the average length of a month. Surprisingly, it works, provided some tricks are used to have the truncation behavior of the integer division work for you.

I tested both versions against your implementation, for every possible day inside the available range, on both an Arduino Uno and on x86.

The binary sizes I get are:

size version
442 original
260 iterative
270 iterative with Y2100_COMPAT
286 arithmetic
310 arithmetic with Y2100_COMPAT

These sizes include the size of the array monthDays[], except for the arithmetic version, where it is not needed. Since monthDays[] is also used by makeTime(), this means that, in a program that uses both breakTime() and makeTime(), the space savings of the arithmetic version are 12 bytes less than suggested by the figures above.

It may be possible to use a similar approach to size-optimize makeTime(). I did not try, as my friend only needed breakTime(). I may give it a try though, if there is interest.

Regards,

Edgar.

Issue with setTime and adjustTime when calling hour() immediatly after.

to recreate:
make a call to hour()
make a call to setTime();
make a call to adjustTime(timezoneCorrection);
make a call to hour();

occasionally hour() will return the time not adjusted for the timezone correction

fix:
change refreshCache to force refresh (sorry code markup appears to not be working for me)

void refreshCache(time_t t, bool bForce = false) {
if (t != cacheTime) {
breakTime(t, tm);
cacheTime = t;
}
}

add new call to refreshCache to both setTime() and adjustTime()

void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
// year can be given as full four digit year or two digts (2010 or 10 for 2010);
//it is converted to years since 1970
if( yr > 99)
yr = yr - 1970;
else
yr += 30;
tm.Year = yr;
tm.Month = mnth;
tm.Day = dy;
tm.Hour = hr;
tm.Minute = min;
tm.Second = sec;
setTime(makeTime(tm));

refreshCache(sysTime,true);
}

void adjustTime(long adjustment) {
sysTime += adjustment;

refreshCache(sysTime,true);
}

Small bug in makeTime function

if tm.Day is zero when calling makTime(tm) the result is wrong.
line:
seconds+= (tm.Day-1) * SECS_PER_DAY;

should be:

if (tm.Day > 0) seconds+= (tm.Day-1) * SECS_PER_DAY;

tzdata time zones

Is there any way to compensate for time zones like the tzdata database with this library?

timeAdjust() anomaly

Pretty new to to this, so it might be beginner's bad luck.
I have been trying out timeAdust() to correct the RTC (DS3231) for a few seconds either way, once a day.
I appreciate that timeAdjust() alters only the running Arduino sketch time.
What I'm finding is that entering negative numbers e.g.time Adjust(-3000), works fine, but with positive numbers, anything over 299 does not work, so timeAdjust(300) does not alter the time, but <=299 does.
Iterations e.g. a 10x for() loop of timeAdjust(60) does not work starts over again at the 5th loop-round.
Is there a positive limit on timeAdjust() ?
Apologies if I'm missing something

Unable to compile with Adafruit libs

Arduino IDE version: 1.8.2
Board version: Arduino AVR boards 1.6.18
OS version: Windows 10 build 1607
Time library version: 1.5

When I compile the sketch I get the "compile for Arduino/Genuino uno error" after collect2.exe: error: ld returned 1 exit status

Here's the sketch:

#include <Adafruit_TFTLCD.h>
#include <TimeLib.h>

int16_t  str_ex, str_ey;
uint16_t str_w, str_h;

void setup(void) {
  Serial.begin(9600);
  setTime(1357041600);
}

void loop(void) {
  delay(1000);
}

Arduino 1.6.6 breaks Time library

There seems to be a new conflict between the ctime time.h and the Arduino Time.h library.
Reproduce by building TimeTeensy3 example. This is on Mac, where the filesystem is ignores case, which may be part of the cause. Verbose build results below.

Arduino: 1.6.6 (Mac OS X), TD: 1.26-beta3, Board: "Teensy 3.2 / 3.1, Serial + Keyboard + Mouse + Joystick, 72 MHz optimized, US English"

/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware" -hardware "/Users/dean/Library/Arduino15/packages" -tools "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/tools-builder" -tools "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr" -tools "/Users/dean/Library/Arduino15/packages" -built-in-libraries "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/libraries" -libraries "/Users/dean/Documents/Arduino/libraries" -fqbn=teensy:avr:teensy31:usb=serialhid,speed=72opt,keys=en-us -ide-version=10606 -build-path "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino"
/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware" -hardware "/Users/dean/Library/Arduino15/packages" -tools "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/tools-builder" -tools "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr" -tools "/Users/dean/Library/Arduino15/packages" -built-in-libraries "/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/libraries" -libraries "/Users/dean/Documents/Arduino/libraries" -fqbn=teensy:avr:teensy31:usb=serialhid,speed=72opt,keys=en-us -ide-version=10606 -build-path "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino"
WARNING: Spurious .git folder in 'Adafruit GFX Library' library
WARNING: Spurious .git folder in 'PID' library
WARNING: Spurious .git folder in 'Audio' library
WARNING: Spurious .git folder in 'FastLED' library
WARNING: Spurious .git folder in 'ILI9341_t3' library
WARNING: Spurious .git folder in 'SparkFun APDS9960 RGB and Gesture Sensor' library
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -M -MG -MP -x c++ -w -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -M -MG -MP -x c++ -w -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -M -MG -MP -x c++ -w -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -M -MG -MP -x c++ -w -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -M -MG -MP -x c++ -w -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -E -CC -x c++ -w  -g -Wall -ffunction-sections -fdata-sections -MMD -nostdlib -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/tools-builder/ctags/5.8-arduino2/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/preproc/ctags_target.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/tools-builder/ctags/5.8-arduino2/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/preproc/ctags_target.cpp"
"/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/tools/avr/../arm/bin/arm-none-eabi-g++" -c -O -g -Wall -ffunction-sections -fdata-sections -MMD -nostdlib -fno-exceptions -felide-constructors -std=gnu++0x -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=126 -DARDUINO=10606 -DF_CPU=72000000 -DARDUINO_ARCH_AVR -DUSB_SERIAL_HID -DLAYOUT_US_ENGLISH "-I/Users/dean/Downloads/Arduino-1.6.6.app/Contents/Java/hardware/teensy/avr/cores/teensy3" "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp" -o "/var/folders/w1/0xxlqytr8xg565001s7pswz80000gn/T/build98fee79b5753e07289d9cb5c4db23e65.tmp/sketch/TimeTeensy3.ino.cpp.o"
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino: In function 'void setup()':
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:11:33: error: 'setSyncProvider' was not declared in this scope
setSyncProvider(getTeensy3Time);
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:16:18: error: 'timeStatus' was not declared in this scope
if (timeStatus()!= timeSet) {
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:16:22: error: 'timeSet' was not declared in this scope
if (timeStatus()!= timeSet) {
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino: In function 'void loop()':
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:28:16: error: 'setTime' was not declared in this scope
setTime(t);
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino: In function 'void digitalClockDisplay()':
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:37:21: error: 'hour' was not declared in this scope
Serial.print(hour());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:38:22: error: 'minute' was not declared in this scope
printDigits(minute());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:39:22: error: 'second' was not declared in this scope
printDigits(second());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:41:20: error: 'day' was not declared in this scope
Serial.print(day());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:43:22: error: 'month' was not declared in this scope
Serial.print(month());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:45:21: error: 'year' was not declared in this scope
Serial.print(year());
^
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino: In function 'long unsigned int processSyncMessage()':
/Users/dean/Documents/Arduino/libraries/TimeLib/examples/TimeTeensy3/TimeTeensy3.ino:61:29: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
if(Serial.find(TIME_HEADER)) {
^
exit status 1
'year' was not declared in this scope

Missing license

The library does not contain any information on the type of license. This makes it legally unusable (at least it is in my opinion under German copyright law).
I found only the LGPL in Time.cpp.
Please add an open source license. A LICENSE file in the repository would clarify the license for the user. Best practise seems to add a license comment in each source file.

Compile errors in Arduino 1.6.7

Hi Paul,

The example TimeNTP_ESP8226Wifi works fine in Arduino 1.6.4, thanks for sharing!

In Arduino 1.6.7 I get plenty compile errors, as I understand caused by the (now) required "Forward Declaration".

If I shuffle declarations and function around, the sketch compiles and upload OK in Arduino 1.6.7.

Thanks,
Gerard.

A way to initiate / force manual synchronization?

Dear Sir,
first of all I really want to say a big thanks to you for the time library.

I need your help though, I am trying to code for a NTP based project, with automatic timezone update / correction etc using time library of course.
For this reason I need to have an "on demand" way to achieve the same result as ex setSyncInterval(120) command achieve but without to have to wait for the next timed sync.
What do you suggest, is there any way to do this? Is your library has a method to triggering this sync when I want independent from the auto sync provided by setSyncInterval?

Thanks and Best Regards,
Mike Kranidis

milli seconds

to synchronize millis() with the second(), I used following workaround:

while(millis()%1000); // wait for milli seconds to be zero before setting new time. setTime(hour, minute, second, day, month, year);

hope this helps someone.
now you can print the time with milli seconds resolution.

Abbreviation of Thursday

The abbreviation of Thursday in "ErrSunMonTueWedThrFriSat" on line 66 in DateStrings.cpp is Thr. Is this on purpose to be compatible with some specification? It is not compatible with the abbreviations used in RFC 2616 where Thu is used for Thursday. Caused me in interesting bugg which resulted in that my HMAC authentication worked on all days except Thursdays :)

Arduino DUE compatibility

This library worked great on my Arduino Mega2560 but when I switched to Arduino DUE it doesn't work anymore.. Is it planned a new release which support also this board?

printDigits?

what happened to printDigits?

I'm having an issue getting this to compile, original issue here:

sudar/Arduino-Makefile#421

I just updated the library to your master.

[thoth@yoga Time]$ pwd
/home/thoth/sketchbook/libraries/Time
[thoth@yoga Time]$ git log -n1
commit cb1e416b846b6d6392599946599f5653f541ada3
Merge: 0bfe218 d66874d
Author: Paul Stoffregen <[email protected]>
Date:   Mon Mar 21 08:30:31 2016 -0700

    Merge pull request #40 from mcauser/esp8266

    ESP8266 eg - Use WiFi.hostByName() to resolve IP from pool of servers

Weekday is 2 today - Monday

Weekday() is showing as 2 today but your notes indicate Sunday is 0 so surely Monday should be 1.

Please advise.

I am guessing you mean Sunday is zero index, but physically day 1.

Found a strange delay that occurs every half hour

I'm using TimeLib.h and TimeAlarms.h for a clock with alarms, the sync is made through NTP server once everyday and I noticed that every 30 minutes now() loses one second (I'm not using now() but hour(), minute() and second()). I've tested my clock for 7 hours, the time at the beginning was the same my smartphone had and after those 7 hours Arduino lost 14 seconds. Is that a power issue? I'm using the USB port, an LCD screen, 3 buttons, a buzzer, a PIR and WiFI Shield.

Possible PIBKAC. Can't locate Time.h in arduino IDE.

I've run the TeensyduinoInstall.linux64 a couple of times and am told that I have installed all files for the Time library but I am unable to locate the Time library in either the arduino IDE or in my file manager. Consequently, my sketch fails to compile. Where are the supposedly installed files being put and, more importantly, how do I get the arduino IDE to use them?

Many humble thanks in advance for your help.
EB

makeTime function

Hi,
I had some problem with this function, When I ask to makeTime what is 0day 0month 0year, it return “4294880896”, which is “6:28:16 2-6-2106”. I had been try to find out the reason for last past hours and couldn't tell why. Please help me

Here is my code.

include<Time.h>

void setup() {
Serial.begin(9600);
}

void loop() {
setTime(sync());
Serial.print(now());
Serial.print(" ");
Serial.print(hour());
Serial.print(':');
Serial.print(minute());
Serial.print(':');
Serial.print(second());
Serial.print(' ');
Serial.print(month());
Serial.print('-');
Serial.print(day());
Serial.print('-');
Serial.println(year());
}
time_t sync() {
tmElements_t tm;
tm.Hour = 0;
tm.Minute = 0;
tm.Second = 0;
tm.Day = 0;
tm.Month = 0;
tm.Year = 0;
return makeTime(tm);
}

Thank you

millis()

Hi,

On the official reference I read this: (http://www.arduino.cc/en/Reference/Millis)

"millis() - Returns the number of milliseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days."

My question: How will the system react to this overflow? Is there a forced re-sync of the time? It's very important for my project because it should guarantee a greater function time.

Thanks in advance!

adjustTime() not compatible with sync provider.

Currently, adjustTime() modifies the actual time.
Because of this, it is not compatible when using a sync provider since the next sync will clobber the adjusted time.
I wrote about this here: http://forum.arduino.cc/index.php?topic=66054.msg2674610#msg2674610
This could be handled with documentation saying don't use with a sync provider.
(which I added to the Arduino Time playground page)
OR
its functionality could be changed such that the offset is saved and is applied to each fetch of the time.
i.e. now() returns the system time adjusted by the adjust amount.

This would allow an offset to be applied to the time retuned by sync providers.
It could be used for a poor mans timzone shift.
i.e. if the sync provider always used UTC like GPS or WWVB. the actual time would be tracked in UTC but then an offset would be applied every time when now() was called so the time the sketch sees is always offset the desired amount.

Easiest way to use setSyncProvider()

It took me some time to figure out how to use this function with various providers.
The argument requested is the address of a function which returns the Unix time in time_t format, which is an unsigned long or uint32_t.

The problem is that addressing a sub-class is not that simple and in my experience it depends on how the clas is built.

The simple solution is to create a new sub which retrieves the value and passes it to the function.

Example:

time_t RDTEpoch32Time()
{
return Epoch32Time(); //get Epoch time from your RTC
}

time_t NTPgetTime()
{
return NTP.getTime(); //get Epoch time from NTP
}

getExternalTime RtcTime = &RDTEpoch32Time;
getExternalTime NtpTime = &NTPgetTime;

To sync the time use:
setSyncProvider(RtcTime);
or
setSyncProvider(NtpTime);

Please notice the sub reference has no (), otherwise it becomes a subroutine call, I guess.
This works!
RDT and NTP are object declared by respective libraries.

DateStrings.cpp:43: error: function definition does not declare parameters

while compiling:

  • TimeSerialDateStrings.pde
  • TimeSerial.pde

ARDUINO 1.0.5 version on OSx Platform

/Users/USER/Documents/Arduino/libraries/time/DateStrings.cpp:43: error: function definition does not declare parameters
/Users/USER/Documents/Arduino/libraries/time/DateStrings.cpp: In function 'char* monthStr(uint8_t)':
/Users/USER/Documents/Arduino/libraries/time/DateStrings.cpp:71: error: 'monthNames_P' was not declared in this scope

Time zone support

Hello,

I'm wondering if time zone is supported in Time library? For example, when I do the conversion from unix time to date, hour, is it possible to specify the timezone for the conversion?

SECS_PER_YEAR is incorrect.

The definition of SECS_PER_YEAR is

52*SECS_PER_WEEK

That's not right, because no day in the Gregorian calendar has 364 days.

To really do it correctly, you need a function that is

365UL*SECS_PER_DAY+(isLeap(year) ? SECS_PER_DAY : 0);

Wrong weekday()

The weekday() function returns wrong daynumbers.

If I understand the documentation right, Sunday is 0, Monday is 1, ... and Saturday is 6.

But yesterday (16.08.2015, Sunday) I tested the library and weekday() gives me a 1, now it's Monday (17.08.2015) and weekday() gives me a 2 for Tuesday...

I used your library to convert an NTP timestamp to human readable strings on an ESP8266. Date and Time is working correct, so I be certain that this is not an issue with a wrong Unix timestamp or my program.

Can you please check this?
Thank You!

PS: I can give you my sketch if you like. Maybe via e-mail.

EDIT:

I take a look in Time.h, the enum "timeDayOfWeek_t" says that Sunday is 1, not 0, and the comment in line 79 too. So your documentation in your readme.txt is wrong.

Why a while-loop?

Considering using this library to represent time I receive from a GSM module using AT commands. To see if it would fit my needs I took a look at the code and found one thing that looked confusing to me. And there were no comment to explain why.

The now() method starts with this while-loop:

  while (millis() - prevMillis >= 1000){      
    sysTime++;
    prevMillis += 1000; 
#ifdef TIME_DRIFT_INFO
    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift     
#endif
  }

It seems to calculate number of seconds that has passed since last call to now() and add to sysTime, correct? If so, why not just write it this way?

sysTime += (millis()-prevMillis)/1000;

I find that much easier to understand what is going on.

IDE 1.6.7 build problem with timelib.h

I get this error in the IDE when I complete an UPLOAD compile once - then try to upload/compile a second time:

Using library Time at version 1.5 in folder: i:\tcode\libraries\Time
GetFileAttributesEx i:\tcode\libraries\Time\DateStrings.cpp i:\tcode\libraries\Time\Time.h: The filename, directory name, or volume label syntax is incorrect.
Error compiling

This is for an ESP8266 (v2.0 and now on v2.1) system on Windows 7.

#include <TimeLib.h>

I've found a workaround where I open the GitHub .ZIP file and copy/overwrite the problem files and then recompile. This works but is a pain to hold both directories open and perform the copy after each failure. It does not work to just copy the files from a second directory as I tried it - but only from the open ZIP.

This must be an IDE issue holding a strange attachment to the files I've never seen before.

This library brought in externally for this library as specified where that owner has not seen this:

NTP sync, status "timeNeedsSync" not working

Hi, I tried the ntp example from this repository. I've set the setSyncInterval to 10s for testing. When i watch the serial monitor it works ok as long as my ethernet cable is plugged in. However when I disconnect the cable the time update stops and timeStatus is 0. I would expect the time to continue on internal clock with timeStatus=1 (timeneedssync). the only way to get things started again is to plug in the networkcable. I want to time functions also to work on internal clock when there is no external sync, isn't that the idea?

[Question] Does now() return adjusted time?

So i'm wondering about the implementation of the now() function and whether takes into account of the adjusting of time zone.

We are currently improving on the docs for the Spark firmware and would be nice to keep it in sync with the Arduino Time Library.

See: particle-iot/docs#257

Thanks!

time_t conflict

With esp8266 2.3.0 arduino core library, when I include the timeLib header file, I get a conflict and cannot compile anymore the core time.c file. I get the error unknown type name 'time_t'.

It seems to be a problem when time.c is compiled with an include to the TimeLib library path. I guess it is because of the overriding time.h definition. ( I don't know if the capital letter makes a difference, I am on windows)

I managed to get the whole things working by compiling first the core libraries and then adding the TimeLib so time.c is already compiled successfully and but that problem annoys me.
Thanks for your help

Compilation error in 1.6.5

When trying to compile with Time and TimeLib I get the following error:

F:\Dropbox\Programs\Arduino\libraries\Time/TimeLib.h:79:28: error: expected unqualified-id before '(' token #define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday ^ States.ino:382:26: note: in expansion of macro 'dayOfWeek' F:\Dropbox\Programs\Arduino\libraries\Time/TimeLib.h:79:39: error: expected primary-expression before '/' token #define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday ^ States.ino:382:26: note: in expansion of macro 'dayOfWeek' F:\Dropbox\Programs\Arduino\libraries\Time/TimeLib.h:79:28: error: expected unqualified-id before '(' token #define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday ^ States.ino:382:63: note: in expansion of macro 'dayOfWeek' F:\Dropbox\Programs\Arduino\libraries\Time/TimeLib.h:79:39: error: expected primary-expression before '/' token #define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday ^ States.ino:382:63: note: in expansion of macro 'dayOfWeek' Error compiling.

I read it may be the order of the includes which I have tried shifting around:

#include "Arduino.h"
#include "Keypad.h"
#include <dht.h>
#include <Encoder.h>
#include <Wire.h>
#include <Time.h>
#include <TimeLib.h>
#include "RTClib.h"
#include <LiquidCrystal.h>
#include <IRremote.h>
#include <NECRemote.h>
#include <SPI.h>
#include "AH_MCP320x.h"
#include "AH_MCP300x.h"
#include "Timer.h"
#include "Globals.h"

relentless use of int - are they strictly required?

There seems to be a bunch of places where int just isn't necessary, ie- hour(), especially:
int hourFormat12(); // the hour now in 12 hour format

Any reason not to use uint_8 in that case? My project's so hard up for space and this could be worthwhile for me to change and I'm looking for some insight as to why int is so frequently the go-to.

Am I missing the reason they're a full int?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.