Read GNSS data with Base HAT

Turn on the GNSS receiver of a Quectel or Telit module on the Base HAT, read its NMEA sentences over USB and print the position with a Python script.

The NMEA sentences carry the position, the time and the satellites in view; the module sends them on a USB serial port while the AT commands go to another.

Requirements

Assemble the Base HAT first, as in Get started with Base HAT, with the USB cable connected.

Required

Hardware

  • Base HAT with a module that has GNSSGNSS depends on the module variant: check it in the module’s datasheet, or with ATI for the firmware version.
  • GNSS antennaOn the GNSS connector of the module, with a clear view of the sky. A SIM card is not needed.

Software

Turn GNSS on and read NMEA data

Read position with Python

For Quectel modules. The script turns GNSS on, reads the NMEA port, checks each RMC sentence against its checksum and prints the position in decimal degrees (negative for south and west).

  1. Save script

    Save the script as gps.py:

    #!/usr/bin/env python3
    """Read the position from the NMEA output of a Quectel module on the Sixfab Base HAT."""
    import serial
    
    AT_PORT = "/dev/ttyUSB2"    # AT command port of the module
    NMEA_PORT = "/dev/ttyUSB1"  # NMEA port of the module
    
    
    def send_at(command):
        """Send one AT command and return the module's answer."""
        with serial.Serial(AT_PORT, 115200, timeout=1) as port:
            port.write((command + "\r").encode())
            return port.read(256).decode(errors="replace")
    
    
    def checksum_ok(sentence):
        """Compare the hex digits after '*' with the XOR of the characters between '$' and '*'."""
        if not sentence.startswith("$") or "*" not in sentence:
            return False
        body, _, given = sentence[1:].partition("*")
        calc = 0
        for char in body:
            calc ^= ord(char)
        return given[:2].upper() == f"{calc:02X}"
    
    
    def to_degrees(value, hemisphere):
        """Convert ddmm.mmmm or dddmm.mmmm to signed decimal degrees."""
        if not value:
            return None
        dot = value.index(".")
        degrees = int(value[:dot - 2]) + float(value[dot - 2:]) / 60
        return -degrees if hemisphere in ("S", "W") else degrees
    
    
    def parse_rmc(sentence):
        """Return the date, time, position and speed of an RMC sentence, or None without a fix."""
        fields = sentence.split("*")[0].split(",")
        if len(fields) < 10 or fields[2] != "A":
            return None
        return {
            "date": fields[9],
            "time": fields[1][:6],
            "latitude": to_degrees(fields[3], fields[4]),
            "longitude": to_degrees(fields[5], fields[6]),
            "speed": float(fields[7] or 0),
        }
    
    
    def main():
        # OK, or +CME ERROR: 504 when GNSS is already on
        print(send_at("AT+QGPS=1").strip())
        with serial.Serial(NMEA_PORT, 115200, timeout=1) as nmea:
            while True:
                line = nmea.readline().decode("ascii", errors="replace").strip()
                # RMC from any constellation: $GPRMC, $GNRMC ...
                if line[3:6] != "RMC" or not checksum_ok(line):
                    continue
                fix = parse_rmc(line)
                if fix is None:
                    print("No fix yet")
                else:
                    print(f"{fix['date']} {fix['time']} UTC  "
                          f"lat {fix['latitude']:.6f}  lon {fix['longitude']:.6f}  "
                          f"speed {fix['speed']} kn")
    
    
    if __name__ == "__main__":
        main()
    

    Change AT_PORT and NMEA_PORT if the ports of the module are numbered differently (find the ports).

  2. Run script

    Run it, and stop it with Ctrl+C:

    python3 gps.py

    With the stream of the example above, it prints one line per second:

    OK
    120121 182142 UTC  lat 37.955407  lon 29.276703  speed 0.0 kn
    120121 182143 UTC  lat 37.955401  lon 29.276710  speed 0.0 kn
    120121 182144 UTC  lat 37.955394  lon 29.276719  speed 0.0 kn

Verify

  1. Check fix

    In the NMEA stream, read the third field of the $GPRMC sentence: A means a valid fix, V no fix yet.

    Result: the third field of $GPRMC is A, and the sentence carries the latitude and the longitude.

Details

Active antenna on legacy boards

On the legacy Cellular IoT Application Shield and Cellular IoT HAT, an active GNSS antenna needs a solder jumper; a passive antenna needs it open. Application Shield:

Cellular IoT HAT, the solder jumper beside the GNSS connector:

Troubleshooting

Check the USB cable, that GNSS is on (AT+QGPS?, AT$GPSP?) and, on Quectel, the output port (AT+QGPSCFG="outport").

No fix yet. Wait a few minutes; the first fix takes longer.

Move the antenna near a window or outdoors, as high as possible, with a clear view of the sky in all directions and away from interference. Try another location. The $GPGSV sentences show the satellites in view and their signal levels.

Check that the module variant and firmware support GNSS (ATI).

Next steps

See also