adafruit / Adafruit_CircuitPython_GPS

GPS parsing module for CircuitPython. Meant to parse NMEA data from serial GPS modules.
MIT License
75 stars 58 forks source link

Allow use of existing sentence for updating #64

Closed andyshinn closed 3 years ago

andyshinn commented 3 years ago

I was wanting to periodically display GPS information and also log it. The problem I was running into is that readline() empties the buffer so that when using update() in the same loop it does not update.

This allows for an example like:

import busio
import time

from sdcard import SDCard
from adafruit_gps import GPS

SPI = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
CS = board.D10
UART_GPS = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)

sd = sdcardio.SDCard(SPI, CS)
vfs = storage.VfsFat(sd)
storage.mount(vfs, "/sd")
gps = GPS(UART_GPS)
timer = time.monotonic()

with open("/sd/test.txt", "ab") as f:
    while True:
        sentence = gps.readline()

        if sentence:
            f.write(sentence)

            if timer + 10 < time.monotonic()
                gps.update(sentence)
                print(f"Satellites: {gps.satellites}")
                print(f"Fix: {gps.fix_quality}")

                if gps.latitude and mygps.longitude:
                    print("Latitude: {0:.6f}".format(gps.latitude))
                    print("Longitude: {0:.6f}".format(gps.longitude))

                print("Time: {}".format(gps.timestamp_utc))

                timer = time.monotonic()
lesamouraipourpre commented 3 years ago

There's no need to call readline() if you're going to call update() as it calls it internally. The following untested code should do what you need:

import busio
import time

from sdcard import SDCard
from adafruit_gps import GPS

SPI = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
CS = board.D10
UART_GPS = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)

sd = sdcardio.SDCard(SPI, CS)
vfs = storage.VfsFat(sd)
storage.mount(vfs, "/sd")
gps = GPS(UART_GPS)
timer = time.monotonic()

with open("/sd/test.txt", "ab") as f:
    while True:
        if gps.update():  # There was a new sentence
            f.write(gps.nmea_sentence())

            if timer + 10 < time.monotonic()
                print(f"Satellites: {gps.satellites}")
                print(f"Fix: {gps.fix_quality}")

                if gps.latitude and gps.longitude:
                    print("Latitude: {0:.6f}".format(gps.latitude))
                    print("Longitude: {0:.6f}".format(gps.longitude))

                print("Time: {}".format(gps.timestamp_utc))

                timer = time.monotonic()
andyshinn commented 3 years ago

Thanks. I missed that property! gps.nmea_sentence.encode() is working with update() in the loop.