sensors_GPS_Satellite_NASA_art-iif.jpg
NASA - Public Domain

The only thing left is an interface to the GPS library to bundle up it's use. The constructor takes a UART object and creates a GPS object with it. It also initializes instance variable in which to cache the GPS location data.

    def __init__(self, uart):
        self._gps = adafruit_gps.GPS(uart, debug=False)
        self._latitude = 0
        self._longitude = 0

Once an instance has been created, it is initialized using the begin method which configures the GPS object.

    def begin(self):
        self._gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
        self._gps.send_command(b'PMTK220,1000')

A big part of using GPS is getting a fix. I.e. locking onto signals from the satellites in view/range. No data can be fetched until that is done. The get_fix method takes care of waiting for a fix to be acquired. Once it has, True is returned. If an exception is raised, False is returned.

    def get_fix(self):
        try:
            logger.debug('Calling gps update')
            self._gps.update()
            logger.debug('Back from gps update')
            while not self._gps.has_fix:
                # Try again if we don't have a fix yet.
                logger.debug('Waiting for fix...')
                time.sleep(0.1)
                self._gps.update()
            return True
        except UnicodeError:
            return False

The read method pulls data from the GPS and caches it. Corresponding properties return the cached data.

    def read(self):
        logger.debug('Reading GPS')
        self._latitude = self._gps.latitude
        self._longitude = self._gps.longitude


    @property
    def latitude(self):
        return self._latitude


    @property
    def longitude(self):
        return self._longitude

Notice that there's no attempt to re-establish a fix since we're only reading from the GPS once, when the system starts up.

This guide was first published on May 01, 2019. It was last updated on Mar 18, 2024.

This page (gps.py) was last updated on Mar 08, 2024.

Text editor powered by tinymce.