arduino time library

6
Arduino Time library The Time library adds timekeeping functionality to Arduino with or without external timekeep ing hardware. It allows a sketch to get the time and date as: second, minute, hour, day, month and year. It also provides time as a standard C timet so elapsed times can be easily calculated and time values shared across different platforms. !pdate: newer versions of Time, TimeAlarms , and "#$%&'(TC are available, featuring more updates for n ewer version of Arduino and compatibility with Arduino "ue. The code is derived from the earlier )layground "ateTime library but is updated to provide an A)I that is more flexible and easier to use. The download includes example sketches illustrating how similar sketch code can  be used with: a (eal Time Clock,Internet *T) time service, +)# time data, "C'' radio signal, and #erial time messages from a computer. To  use all of the features in the library, you-ll need the !")bitewise library, found here. Additional documentation is included in a readme.txt file unctional verview  hour/01 22 The hour now /&34%0  minute/01 22 The minute now /&3560  second/01 22 The second now /&3560  day/01 22 The day now /$3%$0  weekday/01 22 "ay of the week, #unday is day $  month/01 22 The month now /$3$40  year/01 22 The full four digit year: /4&&6,  22 4&$& et c0 there are also functions to return the hour in $4 hour format  hourormat $4/01 22 The hour now in $4 hour format  isA7/01 22 (eturns true if time now is A7 is)7/01 22 (eturns true if time now is )7  now/01 22 (eturns the current time as seconds  22 since 8an $ $6'& The time and date functions can take an optional parameter for the time. This prevents errors if the time rolls over between elements. or example, if a new minute begins  between getting the minute and second, the values will be i nconsistent. !sing the following functions eliminates this problem  timet t 9 now/01 22 #tore the current t ime in time 22 variable t hour/t01 22 (eturns the hour for the given  22 time t  minute/t01 22 (eturns the minute for the given  22 time t  second/t01 22 (eturns the second for the given  22 time t day/t01 22 The day for the given time t  weekday/t01 22 "ay of the week for the given  22 time t month/t01 22 The month for the given time t  year/t01 22 The year for the given time t  unctions for printing out string descriptions for day and month month#tr/0 month#hort#tr/0 day#tr/0 day#hort#tr/0 e aware that a parameter is re;uired for this string functions. The argument is *T the timestamp, e.g. timet, but must be something like month/0. #o month#tr/month/00 or day#tr/weekday/00 will work. #ee also the Time#erial"ate#tring.pde in the download unctions for managing the timer services are:  setTime/t01 22 #et the system time to the  22 give time t  setTime/hr ,min,sec,day, month,yr01 22 Another way to set  22 the time  ad<ustTime/ad<ust ment01 22 Ad<ust system time by adding  22 the ad<ustment value  time#tatus/01 22 Indicates if time has been set and  22 recently synchroni=ed  22 returns one of the following  22 enumerations:  > time*ot#et 22 The time has never been set,  22 the clock started at 8an $ $6'&  > time*eeds#ync 22 The time had been set but a sync  22 attempt did not succeed  > time#et 22 The time is set and is synced  22 Time and "ate values are not vali d if  22 the status is ti me*ot#et. therwise 22 values can be used but t he returned  22 time may have drift ed if the status i s  22 time*eeds#ync. set#ync)rovider/getT imeunction0122 #et the external time  22 provider  set#yncInterval/interval01 22 #et the number of  22 seconds between re3sync  There are many convenience macros in the time.h file for time constants and conversion of time units. !sing the ?ibrary Copy the download to the ?ibrary directory. The Time directory contains the Time library and some example sketches illustrating how the library can be used with various time sources: 3 Time#erial.pde shows Arduino as a clock without external hardware.

Upload: leewei

Post on 06-Jul-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 1/6

Arduino Time libraryThe Time library adds timekeeping functionality to Arduino with or without

external timekeeping hardware. It allows a sketch to get the time and date as:

second, minute, hour, day, month and year. It also provides time as a standard

C timet so elapsed times can be easily calculated and time values shared

across different platforms.

!pdate: newer versions of

Time, TimeAlarms, and "#$%&'(TC are available,

featuring more updates for newer version of Arduino and compatibility with

Arduino "ue.

The code is derived from the earlier )layground "ateTime library but is

updated to provide an A)I that is more flexible and easier to use.

The download includes example sketches illustrating how similar sketch code can

 be used with: a (eal Time Clock,Internet *T) time service, +)# time

data, "C'' radio signal, and #erial time messages from a computer. To use all

of the features in the library, you-ll need the !")bitewise library, found here.

Additional documentation is included in a readme.txt file

unctional verview

 hour/01 22 The hour now /&34%0 

minute/01 22 The minute now /&3560 

second/01 22 The second now /&3560 

day/01 22 The day now /$3%$0 

weekday/01 22 "ay of the week, #unday is day $ 

month/01 22 The month now /$3$40 

year/01 22 The full four digit year: /4&&6, 

22 4&$& etc0

there are also functions to return the hour in $4 hour format

 hourormat$4/01 22 The hour now in $4 hour format

 isA7/01 22 (eturns true if time now is A7

is)7/01 22 (eturns true if time now is )7 

now/01 22 (eturns the current time as seconds 

22 since 8an $ $6'&The time and date functions can take an optional parameter for the time. This prevents

errors if the time rolls over between elements. or example, if a new minute begins

 between getting the minute and second, the values will be inconsistent. !sing the

following functions eliminates this problem

  timet t 9 now/01 22 #tore the current time in time

22 variable thour/t01

22 (eturns the hour for the given  22

time t  minute/t01

22 (eturns the minute for the given  22

time t  second/t01

22 (eturns the second for the given  22

time tday/t01

22 The day for the given time t

  weekday/t01 22 "ay of the week for the given 

22 time t

month/t01 22 The month for the given time t

  year/t01 22 The year for the given time t 

unctions for printing out string descriptions for day and month

month#tr/0

month#hort#tr/0

day#tr/0

day#hort#tr/0

e aware that a parameter is re;uired for this string functions. The argument

is *T the timestamp, e.g. timet, but must be something like month/0. #o

month#tr/month/00 or day#tr/weekday/00 will work.

#ee also the Time#erial"ate#tring.pde in the download

unctions for managing the timer services are:

 setTime/t01 22 #et the system time to the 

22 give time t 

setTime/hr,min,sec,day,month,yr01 22 Another way to set 

22 the time 

ad<ustTime/ad<ustment01 22 Ad<ust system time by adding 

22 the ad<ustment value

 time#tatus/01 22 Indicates if time has been set and 

22 recently synchroni=ed 

22 returns one of the following 

22 enumerations: >

time*ot#et 22 The time has never been set, 

22 the clock started at 8an $ $6'& >

time*eeds#ync 22 The time had been set but a sync 

22 attempt did not succeed >

time#et 22 The time is set and is synced 

22 Time and "ate values are not valid if  

22 the status is time*ot#et. therwise

22 values can be used but the returned 

22 time may have drifted if the status is 

22 time*eeds#ync.

set#ync)rovider/getTimeunction0122 #et the external time 

22 provider  

set#yncInterval/interval01 22 #et the number of  

22 seconds between re3sync 

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

conversion of time units.

!sing the ?ibrary Copy the download to the ?ibrary directory. The Time

directory contains the Time library and some example sketches illustrating

how the library can be used with various time sources:

3 Time#erial.pde shows Arduino as a clock without external hardware.

Page 2: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 2/6

  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.

3 Time(TC uses a "#$%&' (eal Time Clock /or "#%4%$ Chrono"ot (TC>0

to

  provide time synchronization.

  A basic RTC library named !"#$%RTC is included in the

download.  To run this sketch the !"#$%RTC library must be installed.

 & The I'C (!#'#"( interface is very straight forward and

  virtually identical to the register addresses of the

popular !"##%

  and !"#$% RTCs) which means that e*isting code for the

Arduino)

+asic !tamp) Cubloc) and other controllers should work with

no modification.  ,or reference purposes see --

https//www.adafruit.com/products/'00

3 Time*T) uses the Arduino @thernet shield to access time using the

  internet 1TP time service.

  The 1TP protocol uses 2P and the 2dp+ytewise library is

re3uired) see http//bitbucket.org/b4oern/arduino5osc/src/"677%68$0'"f/libra

ries/9thernet/

  1ote This is out of date. ,or Arduino $$'') see the built

in 2dp 1TP e*ample)

  and also see http//arduino.cc/en/Tutorial/2dp1tpClient.

3Time+)# gets time from a +)#

 This re3uires the Tiny:P! and 1ew!oft!erial libraries from

;ikal <art http//arduiniana.org/libraries/Tiny:P! and

http//arduiniana.org/libraries/newsoftserial/

9*ample sketch

The test sketch uses a message on the serial port to set the time. A )rocessing

sketch that sends these messsages is included in the download but you can

test this sketch by sending T$44%B'4&& using the serial monitor /this sets

the time to noon on 8an $ 4&$&0. n a unix system, you can set the time with

the shell command:

Tad<ust93D1 echo TE//E/date FGs0F&>&>ETad<ust00 H 2dev2tty.usbserial3

AD&&Dpym

+et CodeJ

33 edit: The above code did not work for me in my linux terminal, I wrote the

 below script which worked. / I was using =sh and

!no(%0

Tad<ust95.51d9E/date FGs01t9E/echo K&>&>ETad<ust2$K L bc01echo TE/echo EdF

Et Lbc 0 H 2dev2ttyAC7&

+et CodeJ

Ad<ust the Tad<ust value to your time=one and the serial port to your

Arduino.

Minclude NTime.hH

Mdefine TI7@7#+?@* $$ 22 time sync to )C is O@A"@( followed by !nix timet

as ten A#CII digits

Mdefine TI7@O@A"@( -T- 22 Oeader tag for serial time sync message

Mdefine TI7@(@P!@#T ' 22 A#CII bell character re;uests a time sync message

22 T$44%B'4&& 22noon 8an $ 4&$&

void setup/0 Q 

#erial.begin/6&&01R

void loop/0Q

if/#erial.available/0 0

 process#ync7essage/01  R 

if/time#tatus/0 99 time*ot#et0

#erial.println/Kwaiting for sync messageK01 

else

digitalClock"isplay/01

delay/$&&&01R

void digitalClock"isplay/0Q 

22 digital clock display of the time 

#erial.print/hour/001 

 print"igits/minute/001 

 print"igits/second/001 

#erial.print/K K01 

#erial.print/day/001 

#erial.print/K K01 

#erial.print/month/001 

#erial.print/K K01 

#erial.print/year/001

#erial.println/01R

void print"igits/int digits0Q 

22 utility function for digital clock display: prints preceding colon and leading & 

#erial.print/K:K01 

if/digits N $&0 

#erial.print/-&-01 

#erial.print/digits01R

void process#ync7essage/0 Q 

22 if time sync available from serial port, update time and return true 

while/#erial.available/0 H9 TI7@7#+?@* 0Q 22 time message consists of header S

$& A#CII digits 

char c 9 #erial.read/0 1

#erial.print/c01

if/ c 99 TI7@O@A"@( 0 Q

timet pctime 9 &1 

for/int i9&1 i N TI7@7#+?@* 3$1 iFF0Q

c 9 #erial.read/01

Page 3: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 3/6

  if/ c H9 -&- SS c N9 -6-0Q

 pctime 9 /$& > pctime0 F /c 3 -&-0 1 22 convert digits to a numberR

  R

setTime/pctime01 22 #ync Arduino clock to the time received on the serial port  R

RR

+et CodeJ

Oere is a fragment from the Time*T).pde example sketch showing how the

sync)rovider functionality simplifies the sketch code. This sketch gets time

from an Internet time provider /*T)0 using the Arduino @thernet shield. *ote

that the loop code does not re;uire any logic to maintain time sync. The Time

library will automatically monitor *T) and sync the time as necessary.

void setup/0

#erial.begin/6&&01 

@thernet.begin/mac,ip,gateway01

#erial.println/Kwaiting for syncK01 

set#ync)rovider/get*tpTime01 

while/time#tatus/099 time*ot#et0

1 22 wait until the time is set by the sync provider R

void loop/0

Q

if/ now/0 9 prev"isplay0 22update the display only if the time has changed 

 prev"isplay 9 now/01 

digitalClock"isplay/01R

Rvoid digitalClock"isplay/0Q 

22 digital clock display of the time 

#erial.print/hour/001 

 print"igits/minute/001 

 print"igits/second/001 

#erial.print/K K01 

#erial.print/day/001 

#erial.print/K K01 

#erial.print/month/001 

#erial.print/K K01 

#erial.print/year/001

#erial.println/01R

void print"igits/int digits0Q 

22 utility function for digital clock display: prints preceding colon and leading & 

#erial.print/K:K01 

if/digits N $&0 

#erial.print/-&-01

 

#erial.print/digits01R

2>33333333 *T) code 3333333333>2

22 ntp code not shown 3 see Time*T).pde example sketch

volatile keyword

volatile is a keyword known as a variable 3ualifier ) it is usually used before the datatype of avariable) to modify the way in which the compiler and subse3uent program treats the variable.

eclaring a variable volatile is a directive to the compiler. The compiler is software whichtranslates your C/C== code into the machine code) which are the real instructions for the Atmegachip in the Arduino.

!pecifically) it directs the compiler to load the variable from RA; and not from a storageregister) which is a temporary memory location where program variables are stored and manipulated.2nder certain conditions) the value for a variable stored in registers can be inaccurate.

A variable should be declared volatile whenever its value can be changed by something beyond thecontrol of the code section in which it appears) such as a concurrently e*ecuting thread. In theArduino) the only place that this is likely to occur is in sections of code associated withinterrupts) called an interrupt service routine.

9*ample

// toggles >9 when interrupt pin changes state

int pin ? "#@

volatile int state ? >B@void setupDE  pin;odepin) 2TP2TD@  attachInterrupt$) blink) C<A1:9D@F

void loopDE  digitalBritepin) stateD@F

void blinkDE  state ? Gstate@F

attachInterruptD

escription

!pecifies a named Interrupt !ervice Routine I!RD to call when an interrupt occurs. Replaces anyprevious function that was attached to the interrupt. ;ost Arduino boards have two e*ternalinterrupts numbers $ on digital pin 'D and " on digital pin #D. The table below shows theavailable interrupt pins on various boards.

+oard int.$ int." int.' int.# int.6 int.0

2no) 9thernet ' #

;ega'07$ ' # '" '$ "8 "H

>eonardo # ' $ " %

ue   see belowD

The Arduino ue board has powerful interrupt capabilities that allows you to attach an interruptfunction on all available pins. ou can directly specify the pin number in attachInterruptD.

1ote

Inside the attached function) delayCD won(t work and the value returned by millisCD will notincrement. !erial data received while in the function may be lost. ou should declare as volatileany variables that you modify within the attached function. !ee the section on I!Rs below for moreinformation.

2sing Interrupts

Interrupts are useful for making things happen automatically in microcontroller programs) and canhelp solve timing problems. :ood tasks for using an interrupt may include reading a rotary encoder)or monitoring user input.

Page 4: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 4/6

If you wanted to insure that a program always caught the pulses from a rotary encoder) so that itnever misses a pulse) it would make it very tricky to write a program to do anything else) becausethe program would need to constantly poll the sensor lines for the encoder) in order to catchpulses when they occurred. ther sensors have a similar interface dynamic too) such as trying toread a sound sensor that is trying to catch a click) or an infrared slot sensor photoJinterrupterDtrying to catch a coin drop. In all of these situations) using an interrupt can free themicrocontroller to get some other work done while not missing the input.

bout Interrupt !ervice Routines

I!Rs are special kinds of functions that have some uni3ue limitations most other functions do nothave. An I!R cannot have any parameters) and they shouldn(t return anything.

:enerally) an I!R should be as short and fast as possible. If your sketch uses multiple I!Rs) onlyone can run at a time) other interrupts will be ignored turned offD until the current one isfinished. as delayD and millisD both rely on interrupts) they will not work while an I!R isrunning. delay;icrosecondsD) which does not rely on interrupts) will work as e*pected.

Typically global variables are used to pass data between an I!R and the main program. To make surevariables used in an I!R are updated correctly) declare them as volatile.

,or more information on interrupts) see 1ick :ammon(s notes.

!ynta*

attachInterruptinterrupt) I!R) modeD

attachInterruptpin) I!R) modeD Arduino ue only D

Parameters

interrupt the number of the interrupt int D

pin the pin number Arduinoue only D

I!R the I!R to call when the interrupt occurs@ thisfunction must take no parameters and return nothing.This function is sometimes referred to as an interrupt service routine. 

mode

defines when the interrupt should be triggered. ,ourcontstants are predefined as valid values

•   >AB to trigger the interrupt whenever the pin is low)

•   C< 1:9  to trigger the interrupt whenever the pin changesvalue

•   RI!I1: to trigger when the pin goes from low to high)

•   , >>I1: for when the pin goes from high to low.

The ue board allows also

•   <I:< to trigger the interrupt whenever the pin is high.Arduinoue only D

Returns

none

9*ample

int pin ? "#@volatile int state ? >B@

void setupDE  pin;odepin) 2TP2TD@  attachInterrupt$) blink) C<A1:9D@F

void loopDE  digitalBritepin) stateD@F

void blinkDE  state ? Gstate@F

detachInterruptD

escription

Turns off the given interrupt.

!ynta*

detachInterruptinterrupt D

detachInterruptpin D Arduino ue only D

Parameters

• interrupt  the number of the interrupt to disable see attachInterruptD for more detailsD.

• pin  the pin number of the interrupt to disable Arduino ue only D

RP;

Code

ownload RP;.ino

// read RP;volatile int rpmcount ? $@//see http//arduino.cc/en/Reference/Kolatileint rpm ?$@unsigned long lastmillis ? $@void setupDE

 !erial.begin87$$D@attachInterrupt$) rpm5fan) ,A>>I1:D@//interrupt cero $D is on pintwo'D.F

void loopDE 

if millisD J lastmillis ?? "$$$DE /&2ptade every one second) this

will be e3ual to reading frecuency <zD.&/ detachInterrupt$D@ //isable interrupt when calculating

 

rpm ? rpmcount & 7$@ /& Convert frecuency to RP;) note this worksfor one interruption per full rotation. ,or two interrups perfull rotation use rpmcount & #$.&/ 

!erial.printLRP; ?MtLD@ //print the word LRP;L and tab. !erial.printrpmD@ // print the rpm value. !erial.printLMt <z?MtLD@ //print the word L<zL. !erial.printlnrpmcountD@ /&print revolutions per second or <z.And print new line or enter.&/ 

Page 5: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 5/6

 rpmcount ? $@ // Restart the RP; counter lastmillis ? millisD@ // 2ptade lasmillis attachInterrupt$) rpm5fan) ,A>>I1:D@ //enable interrupt  FF

void rpm5fanDE /& this code will be e*ecuted every time theinterrupt $ pin'D gets low.&/  rpmcount==@F

// 9limelec >opez J April '0th '$"#

Code v' Calculate verageDownload RP;5K'.ino

22 read ()7 and calculate average every then readings.const int numreadings ?"$@int readingsNnumreadingsO@unsigned long average ? $@int inde* ? $@unsigned long total@

volatile int rpmcount ? $@//see http//arduino.cc/en/Reference/Kolatile unsigned long rpm ?$@unsigned long lastmillis ? $@

void setupDE

 Serial. begin87$$D@

attachInterrupt$) rpm5fan) A??I*+D@

F

void loopDE

 

if  millisD J lastmillis -? "$$$DE 2>!ptade every one second, this will be e;ualto reading frecuency /O=0.>2

 

detachInterrupt$D@ 22"isable interrupt when calculating

 total ? $@

readingsNinde*O ? rpmcount & 7$@ 2> Convert frecuency to ()7, note: this works for one interruption per full rotation. or two interrups per full rotation userpmcount > %&.>2

 

for  int *?$@ *?8@ *==DE

  total ? total = readingsN*O@

 F

 

average ? total / numreadings@

 rpm ? average@

 

rpmcount ? $@ 22 (estart the ()7 counter 

 inde*==@

 if inde* -? numreadingsDE

  inde*?$@

F

if  millisD - ""$$$DE 22 wait for ()7s average to get stable

 Serial. printK ()7 9 KD@

 Serial. printlnrpmD@

F

 

lastmillis ? millisD@ 22 !ptade lasmillis

  attachInterrupt$) rpm5fan) A??I*+D@ 22enable interrupt

  F

F

void rpm5fanDE 2> this code will be executed every time the interrupt & /pin40gets low.>2

Page 6: Arduino Time Library

8/17/2019 Arduino Time Library

http://slidepdf.com/reader/full/arduino-time-library 6/6

  rpmcount==@

F

The hall effect sensor pin goes to pin ') or interrupt $. The >9 and "$k resistor needed to bethere for this to work. If your fan takes a lot of current) you might need to use an e*ternal powersource.

!imple Circuit ptionIf the internal pullJup resistor for pin ' interrupt $D is enabled by adding the linedigitalBrite') <I:<D@to setupD) then the hall effect sensor can be connected directly to pin ' without re3uiring ane*ternal "$k pullJup resistor and >9. The >9 is actually only serving as a visual indicator inthe original circuit and is not mandatory in for either.

Qe code

//JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

volatile byte half5revolutions@ unsigned int rpm@ unsigned long timeold@ void setupD E  !erial.begin87$$D@  attachInterrupt$) rpm5fun) RI!I1:D@  half5revolutions ? $@  rpm ? $@  timeold ? $@ F void loopD E  if half5revolutions -? '$D E

//2pdate RP; every '$ counts) increase this for better RP; resolution)  //decrease for faster update  rpm ? #$&"$$$/millisD J timeoldD&half5revolutions@

  timeold ? millisD@  half5revolutions ? $@  !erial.printlnrpm)9CD@  F F void rpm5funD E  half5revolutions==@  //9ach rotation) this interrupt function is run twice F

//JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

by zitron 

9dited by 9limelec >opez J April '0th '$"#

// read RP; int half5revolutions ? $@ int rpm ? $@ unsigned long lastmillis ? $@ void setupDE !erial.begin87$$D@attachInterrupt$) rpm5fan) ,A>>I1:D@ F void loopDE if millisD J lastmillis ?? "$$$DE //2ptade every one second) this will be e3ual to readingfrecuency <zD. detachInterrupt$D@//isable interrupt when calculating rpm ? half5revolutions & 7$@ // Convert frecuency to RP;) note this works for one interruptionper full rotation. ,or two interrups per full rotation use half5revolutions & #$. !erial.printLRP; ?MtLD@ //print the word LRP;L and tab. !erial.printrpmD@ // print the rpm value. !erial.printLMt <z?MtLD@ //print the word L<zL. !erial.printlnhalf5revolutionsD@ //print revolutions per second or <z. And print new line orenter. half5revolutions ? $@ // Restart the RP; counter

 lastmillis ? millisD@ // 2ptade lasmillis attachInterrupt$) rpm5fan) ,A>>I1:D@ //enable interrupt  F F // this code will be e*ecuted every time the interrupt $ pin'D gets low. void rpm5fanDE  half5revolutions==@ F