iotivity 0.9.0
[platform/upstream/iotivity.git] / service / notification-manager / SampleApp / arduino / Time / examples / TimeRTCSet / TimeRTCSet.ino
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 included in the download
7  * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
8  */
9
10 #include <Time.h>  
11 #include <Wire.h>  
12 #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
13
14
15 void setup()  {
16   Serial.begin(9600);
17   while (!Serial) ; // Needed for Leonardo only
18   setSyncProvider(RTC.get);   // the function to get the time from the RTC
19   if (timeStatus() != timeSet) 
20      Serial.println("Unable to sync with the RTC");
21   else
22      Serial.println("RTC has set the system time");      
23 }
24
25 void loop()
26 {
27   if (Serial.available()) {
28     time_t t = processSyncMessage();
29     if (t != 0) {
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_HEADER  "T"   // Header tag for serial time sync message
62
63 unsigned long processSyncMessage() {
64   unsigned long pctime = 0L;
65   const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 
66
67   if(Serial.find(TIME_HEADER)) {
68      pctime = Serial.parseInt();
69      return pctime;
70      if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
71        pctime = 0L; // return 0 to indicate that the time is not valid
72      }
73   }
74   return pctime;
75 }
76
77
78
79
80