gps_time_source.py
1 # Simple script using GPS timestamps as RTC time source 2 # The GPS timestamps are available without a fix and keep the track of 3 # time while there is powersource (ie coin cell battery) 4 5 import time 6 import board 7 import busio 8 import rtc 9 import adafruit_gps 10 11 uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) 12 # i2c = busio.I2C(board.SCL, board.SDA) 13 14 gps = adafruit_gps.GPS(uart, debug=False) 15 # gps = adafruit_gps.GPS_GtopI2C(i2c, debug=False) # Use I2C interface 16 17 gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") 18 gps.send_command(b"PMTK220,1000") 19 20 print("Set GPS as time source") 21 rtc.set_time_source(gps) 22 the_rtc = rtc.RTC() 23 24 last_print = time.monotonic() 25 while True: 26 27 gps.update() 28 # Every second print out current time from GPS, RTC and time.localtime() 29 current = time.monotonic() 30 if current - last_print >= 1.0: 31 last_print = current 32 if not gps.timestamp_utc: 33 print("No time data from GPS yet") 34 continue 35 # Time & date from GPS informations 36 print( 37 "Fix timestamp: {:02}/{:02}/{} {:02}:{:02}:{:02}".format( 38 gps.timestamp_utc.tm_mon, # Grab parts of the time from the 39 gps.timestamp_utc.tm_mday, # struct_time object that holds 40 gps.timestamp_utc.tm_year, # the fix time. Note you might 41 gps.timestamp_utc.tm_hour, # not get all data like year, day, 42 gps.timestamp_utc.tm_min, # month! 43 gps.timestamp_utc.tm_sec, 44 ) 45 ) 46 47 # Time & date from internal RTC 48 print( 49 "RTC timestamp: {:02}/{:02}/{} {:02}:{:02}:{:02}".format( 50 the_rtc.datetime.tm_mon, 51 the_rtc.datetime.tm_mday, 52 the_rtc.datetime.tm_year, 53 the_rtc.datetime.tm_hour, 54 the_rtc.datetime.tm_min, 55 the_rtc.datetime.tm_sec, 56 ) 57 ) 58 59 # Time & date from time.localtime() function 60 local_time = time.localtime() 61 62 print( 63 "Local time: {:02}/{:02}/{} {:02}:{:02}:{:02}".format( 64 local_time.tm_mon, 65 local_time.tm_mday, 66 local_time.tm_year, 67 local_time.tm_hour, 68 local_time.tm_min, 69 local_time.tm_sec, 70 ) 71 )