iotivity 0.9.0
[platform/upstream/iotivity.git] / service / notification-manager / SampleApp / arduino / Time / examples / TimeSerial / TimeSerial.ino
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 2013
7  T1357041600  
8  *
9  * A Processing example sketch to automatically send the messages is inclided in the download
10  * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
11  */ 
12  
13 #include <Time.h>  
14
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   while (!Serial) ; // Needed for Leonardo only
21   pinMode(13, OUTPUT);
22   setSyncProvider( requestSync);  //set function to call when sync required
23   Serial.println("Waiting for sync message");
24 }
25
26 void loop(){    
27   if (Serial.available()) {
28     processSyncMessage();
29   }
30   if (timeStatus()!= timeNotSet) {
31     digitalClockDisplay();  
32   }
33   if (timeStatus() == timeSet) {
34     digitalWrite(13, HIGH); // LED on if synced
35   } else {
36     digitalWrite(13, LOW);  // LED off if needs refresh
37   }
38   delay(1000);
39 }
40
41 void digitalClockDisplay(){
42   // digital clock display of the time
43   Serial.print(hour());
44   printDigits(minute());
45   printDigits(second());
46   Serial.print(" ");
47   Serial.print(day());
48   Serial.print(" ");
49   Serial.print(month());
50   Serial.print(" ");
51   Serial.print(year()); 
52   Serial.println(); 
53 }
54
55 void printDigits(int digits){
56   // utility function for digital clock display: prints preceding colon and leading 0
57   Serial.print(":");
58   if(digits < 10)
59     Serial.print('0');
60   Serial.print(digits);
61 }
62
63
64 void processSyncMessage() {
65   unsigned long pctime;
66   const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
67
68   if(Serial.find(TIME_HEADER)) {
69      pctime = Serial.parseInt();
70      if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
71        setTime(pctime); // Sync Arduino clock to the time received on the serial port
72      }
73   }
74 }
75
76 time_t requestSync()
77 {
78   Serial.write(TIME_REQUEST);  
79   return 0; // the time will be sent later in response to serial mesg
80 }
81