• Stars
    star
    1,238
  • Rank 37,008 (Top 0.8 %)
  • Language
    C++
  • Created almost 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Time library for Arduino

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.

More Repositories

1

Audio

Teensy Audio Library
C++
955
star
2

OneWire

Library for Dallas/Maxim 1-Wire Chips
C++
542
star
3

Encoder

Quadrature Encoder Library for Arduino
C++
489
star
4

cores

Teensy Core Libraries for Arduino
C
474
star
5

TimerOne

TimerOne Library with optimization and expanded hardware support
C++
438
star
6

CapacitiveSensor

Detect touch or proximity by capacitve sensing
C++
360
star
7

teensy_loader_cli

Command line Teensy Loader
C
316
star
8

AltSoftSerial

Software emulated serial using hardware timers for improved compatibility
C++
308
star
9

SerialFlash

Library for using SPI Flash memory with a filesystem-like interface
C++
296
star
10

OctoWS2811

Control thousands of WS2811/2812 LEDs at video refresh speeds
C++
247
star
11

RadioHead

Version of RadioHead library for Teensy boards
C++
237
star
12

ILI9341_t3

Optimized ILI9341 TFT Library
C
224
star
13

XPT2046_Touchscreen

Touchscreen Arduino Library for XPT2046 Touch Controller Chip
C++
208
star
14

USBHost_t36

USB Host Library for Teensy 3.6 and 4.0
C++
166
star
15

TimeAlarms

Time library add-on, schedule alarms to occur at specific dates/times
C++
159
star
16

MahonyAHRS

C++
152
star
17

WS2812Serial

Non-Blocking WS2812 LED Library
C++
137
star
18

FreqCount

Measures the frequency of a signal by counting the number of pulses during a fixed time.
C
136
star
19

PS2Keyboard

PS/2 Keyboard Library for Arduino
C++
132
star
20

DS1307RTC

Use a DS1307 Real Time Clock chip with the Time library
C++
127
star
21

Ethernet

Ethernet library for Teensy (Wiznet W5100 / W5200 / W5500)
C++
125
star
22

SPI

SPI library for Teensy & Arduino IDE
C++
119
star
23

MsTimer2

Run a function using a timer
C++
104
star
24

CoreMark

Benchmark CPU Performance on Arduino Compatible Boards
C
102
star
25

DmxSimple

C++
90
star
26

EEPROM

C++
76
star
27

TimerThree

TimerThree Library with optimization and expanded hardware support
C++
75
star
28

LittleFS

C
71
star
29

Tlc5940

16 channel PWM LED driver based on the Texas Instruments TLC5940 chip.
C
71
star
30

SD

C++
67
star
31

FreqMeasure

Measures the elapsed time during each cycle of an input frequency.
C
64
star
32

MotionCal

Motion Sensor Calibration Tool
C
63
star
33

NXPMotionSense

NXP Motion Sensors for Teensy and Arduino
C++
61
star
34

ILI9341_fonts

Extra fonts for use with ILI9341_t3
C
50
star
35

hid_listen

C
47
star
36

PulsePosition

Multiple High-Res Input & Output PPM Encoded Signal Streams on Teensy 4.x, 3.x & LC
C++
45
star
37

FreqMeasureMulti

Measures the elapsed time during each cycle of up to 8 input frequencies.
C++
34
star
38

ST7735_t3

Teensy 3.x Optimized Version of Adafruit_ST7735 (1.8 inch TFT Display)
C
32
star
39

X-Plane_Plugin

TeensyControls Plugin for X-Plane Flight Simulator
C
31
star
40

MakerFaire2017

Monolith Synth
C++
24
star
41

Bridge

Communicate between Teensy & Raspberry Pi - similar to Arduino Yun
Arduino
24
star
42

RSA_signature_speed

Simple CPU speed benchmark
C
24
star
43

ARM-Toolchain

Shell
23
star
44

PWMServo

Control RC Servo motors with interrupt-resilient PWM
C++
23
star
45

Teensyduino_Examples

Examples for Teensyduino, installed into Arduino's File > Examples > Teensy menu
C++
22
star
46

teensy41_psram_memtest

C++
21
star
47

teensy41_extram

C
20
star
48

Wire

Wire library used on Teensy boards
C++
20
star
49

LedDisplay

Print text to an Avago HCMS-29xx LED display
C++
19
star
50

FrequencyTimer2

Create a zero jitter frequency output, and run your own function on each period.
C++
19
star
51

teensy41_ethernet

C
15
star
52

CryptoAccel

Assembly
15
star
53

TouchGuitar

Arduino
13
star
54

arm_math

C
11
star
55

k66_ethernet

Experiments with K66 Ethernet
Arduino
10
star
56

USB-Serial-Print-Speed-Test

How many lines/second can your Arduino print to the serial monitor?
C++
10
star
57

AVR_DTMF

Efficient 8 bit AVR-based DTMF Decoding
C
10
star
58

Tectonic_Pitch_Shift

C++
9
star
59

FreqCountMany

Measure 10 frequencies with Teensy 4.0 & 4.1
C++
9
star
60

ARM_Toolchain_2014q1_Source

GCC ARM Toolchain Source - for running Arduino on Raspberry Pi
Shell
9
star
61

secure_plugin

Teensy 4 Security plugin for Arduino IDE
Java
8
star
62

SoundfontDecoder

Python
8
star
63

ST7789_t3

C++
7
star
64

Arduino-1.8.9-Teensyduino

Java
7
star
65

ht1632c

Objective-C
7
star
66

Arduino-1.8.5-Teensyduino

C
7
star
67

TopOctaveGenerator

C++
6
star
68

Verify_All_Arduino_Libraries

Perl
6
star
69

teensy_size

C
6
star
70

AudioZero

Allows playing audio files from an SD card.
C++
6
star
71

Arduino-1.8.13-Teensyduino

Java
5
star
72

Arduino-examples-for-Teensyduino

The slightly modified examples for Teensyduino
Arduino
5
star
73

TalkieKeyboards

Five 104-key keyboards trigger speaking 520 words
C
5
star
74

LargeSamplePlayer

C++
5
star
75

Arduino-1.6.0-Teensyduino

C
5
star
76

USB_Tester

C++
5
star
77

hab_tests

C
5
star
78

teardown2018

LED Visualization Shown at Teardown 2018 Hardware Conference
C++
5
star
79

Arduino-1.8.19-Teensyduino

Java
4
star
80

timecode_now

C
4
star
81

Arduino-1.8.8-Teensyduino

Java
4
star
82

Arduino-1.8.10-Teensyduino

Java
4
star
83

Lighting_Controller

C++
4
star
84

SerialDiscovery_JSON

C
4
star
85

Phazerville-Screen-Capture

C++
4
star
86

Arduino-1.8.7-Teensyduino

Java
3
star
87

MyFault

C
3
star
88

Arduino-1.8.12-Teensyduino

Java
3
star
89

ARM_Toolchain_2016q3_Source

Shell
3
star
90

precompile_helper

Help arduino-builder to generate a precompiled Arduino.h header, to speed up compiling Arduino sketches
C
3
star
91

Arduino-1.6.4-Teensyduino

C
3
star
92

AudioWorkshop2015

Audio Workshop at Hackaday Supercon 2015
3
star
93

antplus

Stand-alone Ant Plus code from Michael McElligott
C++
3
star
94

Arduino-1.8.14-Teensyduino

Java
3
star
95

Video_Start_Button

C
2
star
96

Noritake_VFD_CUY

Noritake_VFD_CUY: C++ code library and demo files
C++
2
star
97

Arduino_Dev_List_Topics

2
star
98

Servo

C++
2
star
99

Magnetometers_Test

Simple Magnetometer Testing
C++
2
star
100

StepperPulse

Experiments with DMA to efficiently generate stepper pulse & direction
Arduino
2
star