iotivity 0.9.0
[platform/upstream/iotivity.git] / service / notification-manager / SampleApp / arduino / Time / examples / TimeGPS / TimeGPS.ino
1 /*
2  * TimeGPS.pde
3  * example code illustrating time synced from a GPS
4  * 
5  */
6
7 #include <Time.h>
8 #include <TinyGPS.h>       // http://arduiniana.org/libraries/TinyGPS/
9 #include <SoftwareSerial.h>
10 // TinyGPS and SoftwareSerial libraries are the work of Mikal Hart
11
12 SoftwareSerial SerialGPS = SoftwareSerial(10, 11);  // receive on pin 10
13 TinyGPS gps; 
14
15 // To use a hardware serial port, which is far more efficient than
16 // SoftwareSerial, uncomment this line and remove SoftwareSerial
17 //#define SerialGPS Serial1
18
19 // Offset hours from gps time (UTC)
20 const int offset = 1;   // Central European Time
21 //const int offset = -5;  // Eastern Standard Time (USA)
22 //const int offset = -4;  // Eastern Daylight Time (USA)
23 //const int offset = -8;  // Pacific Standard Time (USA)
24 //const int offset = -7;  // Pacific Daylight Time (USA)
25
26 // Ideally, it should be possible to learn the time zone
27 // based on the GPS position data.  However, that would
28 // require a complex library, probably incorporating some
29 // sort of database using Eric Muller's time zone shape
30 // maps, at http://efele.net/maps/tz/
31
32 time_t prevDisplay = 0; // when the digital clock was displayed
33
34 void setup()
35 {
36   Serial.begin(9600);
37   while (!Serial) ; // Needed for Leonardo only
38   SerialGPS.begin(4800);
39   Serial.println("Waiting for GPS time ... ");
40 }
41
42 void loop()
43 {
44   while (SerialGPS.available()) {
45     if (gps.encode(SerialGPS.read())) { // process gps messages
46       // when TinyGPS reports new data...
47       unsigned long age;
48       int Year;
49       byte Month, Day, Hour, Minute, Second;
50       gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age);
51       if (age < 500) {
52         // set the Time to the latest GPS reading
53         setTime(Hour, Minute, Second, Day, Month, Year);
54         adjustTime(offset * SECS_PER_HOUR);
55       }
56     }
57   }
58   if (timeStatus()!= timeNotSet) {
59     if (now() != prevDisplay) { //update the display only if the time has changed
60       prevDisplay = now();
61       digitalClockDisplay();  
62     }
63   }
64 }
65
66 void digitalClockDisplay(){
67   // digital clock display of the time
68   Serial.print(hour());
69   printDigits(minute());
70   printDigits(second());
71   Serial.print(" ");
72   Serial.print(day());
73   Serial.print(" ");
74   Serial.print(month());
75   Serial.print(" ");
76   Serial.print(year()); 
77   Serial.println(); 
78 }
79
80 void printDigits(int digits) {
81   // utility function for digital clock display: prints preceding colon and leading 0
82   Serial.print(":");
83   if(digits < 10)
84     Serial.print('0');
85   Serial.print(digits);
86 }
87