]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/Time/Examples/TimeGPS/TimeGPS.pde
first commit
[arduino] / books / pdummies / Libraries / Time / Examples / TimeGPS / TimeGPS.pde
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 <NewSoftSerial.h>  //http://arduiniana.org/libraries/newsoftserial/
10 // GPS and NewSoftSerial libraries are the work of Mikal Hart
11
12 TinyGPS gps; 
13 NewSoftSerial serial_gps =  NewSoftSerial(3, 2);  // receive on pin 3
14
15 const int offset = 1;   // offset hours from gps time (UTC)
16 time_t prevDisplay = 0; // when the digital clock was displayed
17
18 void setup()
19 {
20   Serial.begin(9600);
21   serial_gps.begin(4800);
22   Serial.println("Waiting for GPS time ... ");
23   setSyncProvider(gpsTimeSync);
24 }
25
26 void loop()
27 {
28   while (serial_gps.available()) 
29   {
30     gps.encode(serial_gps.read()); // process gps messages
31   }
32   if(timeStatus()!= timeNotSet) 
33   {
34      if( now() != prevDisplay) //update the display only if the time has changed
35      {
36        prevDisplay = now();
37        digitalClockDisplay();  
38      }
39   }      
40 }
41
42 void digitalClockDisplay(){
43   // digital clock display of the time
44   Serial.print(hour());
45   printDigits(minute());
46   printDigits(second());
47   Serial.print(" ");
48   Serial.print(day());
49   Serial.print(" ");
50   Serial.print(month());
51   Serial.print(" ");
52   Serial.print(year()); 
53   Serial.println(); 
54 }
55
56 void printDigits(int digits){
57   // utility function for digital clock display: prints preceding colon and leading 0
58   Serial.print(":");
59   if(digits < 10)
60     Serial.print('0');
61   Serial.print(digits);
62 }
63
64 time_t gpsTimeSync(){
65   //  returns time if avail from gps, else returns 0
66   unsigned long fix_age = 0 ;
67   gps.get_datetime(NULL,NULL, &fix_age);
68   unsigned long time_since_last_fix;
69   if(fix_age < 1000)
70     return gpsTimeToArduinoTime(); // return time only if updated recently by gps  
71   return 0;
72 }
73
74 time_t gpsTimeToArduinoTime(){
75   // returns time_t from gps date and time with the given offset hours
76   tmElements_t tm;
77   int year;
78   gps.crack_datetime(&year, &tm.Month, &tm.Day, &tm.Hour, &tm.Minute, &tm.Second, NULL, NULL);
79   tm.Year = year - 1970; 
80   time_t time = makeTime(tm);
81   return time + (offset * SECS_PER_HOUR);
82 }