]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/Time/Examples/TimeSerial/TimeSerial.pde
first commit
[arduino] / books / pdummies / Libraries / Time / Examples / TimeSerial / TimeSerial.pde
1 /* 
2  * TimeSerial.pde
3  * example code illustrating Time library set through serial port messages.
4  *
5  * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
6  * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2010
7  T1262347200  
8  *
9  * A Processing example sketch to automatically send the messages is inclided in the download
10  */ 
11  
12 #include <Time.h>  
13
14 #define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
15 #define TIME_HEADER  'T'   // Header tag for serial time sync message
16 #define TIME_REQUEST  7    // ASCII bell character requests a time sync message 
17
18 void setup()  {
19   Serial.begin(9600);
20   setSyncProvider( requestSync);  //set function to call when sync required
21   Serial.println("Waiting for sync message");
22 }
23
24 void loop(){    
25   if(Serial.available() ) 
26   {
27     processSyncMessage();
28   }
29   if(timeStatus()!= timeNotSet)   
30   {
31     digitalWrite(13,timeStatus() == timeSet); // on if synced, off if needs refresh  
32     digitalClockDisplay();  
33   }
34   delay(1000);
35 }
36
37 void digitalClockDisplay(){
38   // digital clock display of the time
39   Serial.print(hour());
40   printDigits(minute());
41   printDigits(second());
42   Serial.print(" ");
43   Serial.print(day());
44   Serial.print(" ");
45   Serial.print(month());
46   Serial.print(" ");
47   Serial.print(year()); 
48   Serial.println(); 
49 }
50
51 void printDigits(int digits){
52   // utility function for digital clock display: prints preceding colon and leading 0
53   Serial.print(":");
54   if(digits < 10)
55     Serial.print('0');
56   Serial.print(digits);
57 }
58
59 void processSyncMessage() {
60   // if time sync available from serial port, update time and return true
61   while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
62     char c = Serial.read() ; 
63     Serial.print(c);  
64     if( c == TIME_HEADER ) {       
65       time_t pctime = 0;
66       for(int i=0; i < TIME_MSG_LEN -1; i++){   
67         c = Serial.read();          
68         if( c >= '0' && c <= '9'){   
69           pctime = (10 * pctime) + (c - '0') ; // convert digits to a number    
70         }
71       }   
72       setTime(pctime);   // Sync Arduino clock to the time received on the serial port
73     }  
74   }
75 }
76
77 time_t requestSync()
78 {
79   Serial.print(TIME_REQUEST,BYTE);  
80   return 0; // the time will be sent later in response to serial mesg
81 }
82 \r