Arduino Time Library Introduction


The Time library provides you with timekeeping functionality on the Arduino. The latest version of the library is documented here.

To install it, search for Time in the Library Manager and install the library by Michael Margolis.You’ll have to scroll a bit to find this library.

Once the library is installed, if you go to File → Examples → Time, you will be able to see several examples of integrating this library with various sources: GPS, NTP, RTC, etc.


The basic idea is that you can set time using the functions −

setTime(hours, minutes, seconds, days, months, years);

OR,

setTime(t);

where t is the special time_t variable type, which is the number of seconds elapsed since 1970. You may also know this as the epoch time.

Alternatively, you can set a sync source, setSyncProvider(getTimeFunction) and the sync interval setSyncInterval(seconds). This way, if you have a source which has a getTime() function, you can use it as a sync source and keep updating the time every N seconds, specified in the setSyncInterval argument. An illustration is given in the TimeRTC example.

Once the time is set through any of the above ways, the Time library uses the internal millis() function to maintain time.

Example

For example, in the following code, I’ve set an arbitrary time value in the setup and I’m printing the time value in loop at intervals of 1 second.

#include <TimeLib.h>
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   setTime(3, 10, 30, 24, 5, 2021);
}

void loop() {
   // put your main code here, to run repeatedly:
   digitalClockDisplay();
   delay(1000);
}

void digitalClockDisplay(){
   // digital clock display of the time
   Serial.print(hour());
   printDigits(minute());
   printDigits(second());
   Serial.print(" ");
   Serial.print(day());
   Serial.print(" ");
   Serial.print(month());
   Serial.print(" ");
   Serial.print(year());
   Serial.println();
}

void printDigits(int digits) {
   // utility function for digital clock display: prints preceding colon and leading 0
   Serial.print(":");
   if(digits < 10)
      Serial.print('0');
      Serial.print(digits);
}

Output

The Serial Monitor output is −

As you can see, the time is incrementing every second. Thus, once the time is set, this library can maintain it, and the best part is that it can interface with various time sources like GPS, RTC, NTP, etc. You are encouraged to go through the documentation of this library and also the examples that come along with this library.

Updated on: 02-Aug-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements