3 * example code illustrating time synced from a GPS
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
13 NewSoftSerial serial_gps = NewSoftSerial(3, 2); // receive on pin 3
15 const int offset = 1; // offset hours from gps time (UTC)
16 time_t prevDisplay = 0; // when the digital clock was displayed
21 serial_gps.begin(4800);
22 Serial.println("Waiting for GPS time ... ");
23 setSyncProvider(gpsTimeSync);
28 while (serial_gps.available())
30 gps.encode(serial_gps.read()); // process gps messages
32 if(timeStatus()!= timeNotSet)
34 if( now() != prevDisplay) //update the display only if the time has changed
37 digitalClockDisplay();
42 void digitalClockDisplay(){
43 // digital clock display of the time
45 printDigits(minute());
46 printDigits(second());
50 Serial.print(month());
56 void printDigits(int digits){
57 // utility function for digital clock display: prints preceding colon and leading 0
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;
70 return gpsTimeToArduinoTime(); // return time only if updated recently by gps
74 time_t gpsTimeToArduinoTime(){
75 // returns time_t from gps date and time with the given offset hours
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);