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