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 // uncomment these lines if pull-up resistors are wanted
24 // pinMode( inputPins[i], INPUT_PULLUP);
31 for(int i=0; i < nbrInputPins; i++)
33 boolean val = digitalRead(inputPins[i]);
36 time_t duration = 0; // the time since the previous event
38 time_t timeNow = now();
39 if(prevEventTime[i] > 0)
40 // if this was not the first state change, calculate the time from the previous change
41 duration = duration = timeNow - prevEventTime[i];
42 logEvent(inputPins[i], val, timeNow, duration ); // log the event
43 prevEventTime[i] = timeNow; // store the time for this event
48 void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
53 Serial.print(" went High at ");
55 Serial.print(" went Low at ");
58 // only display duration if greater than 0
59 Serial.print(", Duration was ");
60 showDuration(duration);
66 void showTime(time_t t){
67 // display the given time
68 Serial.print(hour(t));
69 printDigits(minute(t));
70 printDigits(second(t));
74 Serial.print(month(t));
76 Serial.print(year(t));
79 void printDigits(int digits){
80 // utility function for digital clock display: prints preceding colon and leading 0
87 void showDuration(time_t duration){
88 // prints the duration in days, hours, minutes and seconds
89 if(duration >= SECS_PER_DAY){
90 Serial.print(duration / SECS_PER_DAY);
91 Serial.print(" day(s) ");
92 duration = duration % SECS_PER_DAY;
94 if(duration >= SECS_PER_HOUR){
95 Serial.print(duration / SECS_PER_HOUR);
96 Serial.print(" hour(s) ");
97 duration = duration % SECS_PER_HOUR;
99 if(duration >= SECS_PER_MIN){
100 Serial.print(duration / SECS_PER_MIN);
101 Serial.print(" minute(s) ");
102 duration = duration % SECS_PER_MIN;
104 Serial.print(duration);
105 Serial.print(" second(s) ");