]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/Time/Examples/TimeRTCSet/TimeRTCSet.pde
first commit
[arduino] / books / pdummies / Libraries / Time / Examples / TimeRTCSet / TimeRTCSet.pde
1 /*
2  * TimeRTCSet.pde
3  * example code illustrating Time library with Real Time Clock.
4  *
5  * RTC clock is set in response to serial port time message 
6  * A Processing example sketch to set the time is inclided in the download
7  */
8
9 #include <Time.h>  
10 #include <Wire.h>  
11 #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
12
13
14 void setup()  {
15   Serial.begin(9600);
16   setSyncProvider(RTC.get);   // the function to get the time from the RTC
17   if(timeStatus()!= timeSet) 
18      Serial.println("Unable to sync with the RTC");
19   else
20      Serial.println("RTC has set the system time");      
21 }
22
23 void loop()
24 {
25   if(Serial.available())
26   {
27      time_t t = processSyncMessage();
28      if(t >0)
29      {
30         RTC.set(t);   // set the RTC and the system time to the received value
31         setTime(t);          
32      }
33   }
34    digitalClockDisplay();  
35    delay(1000);
36 }
37
38 void digitalClockDisplay(){
39   // digital clock display of the time
40   Serial.print(hour());
41   printDigits(minute());
42   printDigits(second());
43   Serial.print(" ");
44   Serial.print(day());
45   Serial.print(" ");
46   Serial.print(month());
47   Serial.print(" ");
48   Serial.print(year()); 
49   Serial.println(); 
50 }
51
52 void printDigits(int digits){
53   // utility function for digital clock display: prints preceding colon and leading 0
54   Serial.print(":");
55   if(digits < 10)
56     Serial.print('0');
57   Serial.print(digits);
58 }
59
60 /*  code to process time sync messages from the serial port   */
61 #define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
62 #define TIME_HEADER  'T'   // Header tag for serial time sync message
63
64 time_t processSyncMessage() {
65   // return the time if a valid sync message is received on the serial port.
66   while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
67     char c = Serial.read() ; 
68     Serial.print(c);  
69     if( c == TIME_HEADER ) {       
70       time_t pctime = 0;
71       for(int i=0; i < TIME_MSG_LEN -1; i++){   
72         c = Serial.read();          
73         if( c >= '0' && c <= '9'){   
74           pctime = (10 * pctime) + (c - '0') ; // convert digits to a number    
75         }
76       }   
77       return pctime; 
78     }  
79   }
80   return 0;
81 }
82 \r