3 * example code illustrating adding and subtracting Time.
5 * this sketch logs pin state change events
6 * the time of the event and time since the previous event is calculated and sent to the serial port.
11 #include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
13 const int nbrInputPins = 6; // monitor 6 digital pins
14 const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor
15 boolean state[nbrInputPins] ; // the state of the monitored pins
16 time_t prevEventTime[nbrInputPins] ; // the time of the previous event
20 setSyncProvider(RTC.get); // the function to sync the time from the RTC
21 for(int i=0; i < nbrInputPins; i++){
22 pinMode( inputPins[i], INPUT);
23 // digitalWrite( inputPins[i], HIGH); // uncomment these lines if
24 // state[i] = HIGH; // pull-up resistors are wanted
30 for(int i=0; i < nbrInputPins; i++)
32 boolean val = digitalRead(inputPins[i]);
35 time_t duration = 0; // the time since the previous event
37 time_t timeNow = now();
38 if(prevEventTime[i] > 0)
39 // if this was not the first state change, calculate the time from the previous change
40 duration = duration = timeNow - prevEventTime[i];
41 logEvent(inputPins[i], val, timeNow, duration ); // log the event
42 prevEventTime[i] = timeNow; // store the time for this event
47 void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
52 Serial.print(" went High at ");
54 Serial.print(" went Low at ");
57 // only display duration if greater than 0
58 Serial.print(", Duration was ");
59 showDuration(duration);
65 void showTime(time_t t){
66 // display the given time
67 Serial.print(hour(t));
68 printDigits(minute(t));
69 printDigits(second(t));
73 Serial.print(month(t));
75 Serial.print(year(t));
78 void printDigits(int digits){
79 // utility function for digital clock display: prints preceding colon and leading 0
86 void showDuration(time_t duration){
87 // prints the duration in days, hours, minutes and seconds
88 if(duration >= SECS_PER_DAY){
89 Serial.print(duration / SECS_PER_DAY);
90 Serial.print(" day(s) ");
91 duration = duration % SECS_PER_DAY;
93 if(duration >= SECS_PER_HOUR){
94 Serial.print(duration / SECS_PER_HOUR);
95 Serial.print(" hour(s) ");
96 duration = duration % SECS_PER_HOUR;
98 if(duration >= SECS_PER_MIN){
99 Serial.print(duration / SECS_PER_MIN);
100 Serial.print(" minute(s) ");
101 duration = duration % SECS_PER_MIN;
103 Serial.print(duration);
104 Serial.print(" second(s) ");