Raspberry Pi Pico: NEO-M8N GPS Logger and Display on Google Earth (MicroPython)

Getting started guide for the NEO-M8N GPS Module with the Raspberry Pi Pico. Learn how to interface the module with the Pico board and get data about location and time. We’ll also create a GPS logger project with a microSD card to record your GPS position over time. Then, you’ll learn how to use that GPS data on Google Earth to display a path.

Raspberry Pi Pico with NEO-M8N GPS Module: GPS Logger and Display on Google Earth (MicroPython)

New to the Raspberry Pi Pico? Check out Learn Raspberry Pi Pico/Pico W with MicroPython eBook.

In this tutorial, you’ll learn the following:

  • Wire the NEO-M8N GPS module to the Raspberry Pi Pico via serial;
  • Get raw GPS data;
  • Parse raw data to obtain selected and readable GPS information;
  • Get your current location;
  • Log the location to a file on the microSD card;
  • Transform your data into a .kml file that Google Earth can read;
  • Upload the .kml file to Google Earth to display a path.

Table of Contents

We’ll cover the following subjects:

Prerequisites – MicroPython Firmware

To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.

The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.

Introducing the NEO-M8N GPS Module

The NEO-M8N GPS module is one of the most popular GPS receivers used with microcontrollers in navigation and tracking projects. It can get data about latitude, longitude, altitude, and time.

It supports multiple satellite systems, including GPS, Galileo, GLONASS, and BeiDou. It offers better satellite tracking than the NEO-6M, making it more reliable in challenging conditions.

NEO-M8N-GPS-Module

According to the datasheet, it has a horizontal position accuracy of 2.5 to 4 meters and quick startup times (1 second for hot start, 26–57 seconds for cold start—expect longer times if you’re close to buildings).

The module includes a backup battery, built-in EEPROM, and an LED indicator that blinks when a position fix is achieved.

RPi Pico NEO-M8N Position Fix - Blinking LED

This module typically comes with a ceramic GPS antenna. But, you can change it to any other compatible antenna that might suit your project better. For example, I like to use the one at the right in the picture below because it is waterproof, and the antenna comes with a long cable which allows for more flexibility.

antennas for GPS modules

The NEO-M8N GPS Module communicates with a microcontroller using Serial communication protocol, and works with standard NMEA sentences. NMEA stands for National Marine Electronics Association, and in the world of GPS, it is a standard data format supported by GPS manufacturers.

Where to buy?

You can check our Maker Advisor Tools page to compare the NEO-M8N GPS receiver module price in different stores:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Wiring the NEO-M8N GPS Module to the Raspberry Pi Pico

Wiring the NEO-M8N GPS Module to the Raspberry Pi Pico

To get data from the NEO-6M GPS module, we need to establish a serial communication. The Raspberry Pi Pico has the following options for UART pins:

UART InterfaceTX GPIOsRX GPIOs
UART0GPIO0, GPIO12, GPIO16GPIO1, GPIO13, GPIO17
UART1GPIO4, GPIO8GPIO5, GPIO9

We’ll use UART 1 and GPIO 4 (TX) and GPIO 5 (RX).

Wiring NEO-6M GPS Module to the Raspberry Pi Pico
NEO-6M GPS ModuleRaspberry Pi Pico
VCC3V3
RXTX (GPIO 4) (Pin 6)
TXRX (GPIO 5) (Pin 7)
GNDGND

Related article: Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained

Getting Raw GPS Data – Testing the NEO-M8N GPS Module with the Raspberry Pi Pico (MicroPython)

To get raw GPS data you just need to start a serial communication with the GPS module and read the available data.

Getting Raw GPS Data - Testing the NEO-M8N GPS Module with the Raspberry Pi Pico

The following code establishes a serial communication with the GPS module and reads the available data.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-neo-m8n-gps-micropython/

import machine
from time import sleep

# Define the UART pins and create a UART object
gps_serial = machine.UART(1, baudrate=9600, tx=4, rx=5)

while True:
    if gps_serial.any():
        line = gps_serial.readline()  # Read a complete line from the UART
        if line:
            line = line.decode('utf-8')
            print(line.strip())
    sleep(0.5)

View raw code

Testing the Code

After establishing a connection with the board using Thonny IDE, run the previous code.

Make sure the antenna is connected and that the module or antenna is placed outside or next to a window so that it can get data from the satellites.

active GPS antenna for NEO-6M

The module’s blue LED will start blinking when it finds a position fix—this might take a few minutes on the first run.

The shell will display NMEA sentences with GPS data.

Raspberry Pi Pico with Neo-M8N GPS Module - Get Raw GPS Data

Important: If you’re running this sketch for the first time, it may take a few minutes until the module gets a position fix. You’ll start getting actual data when the blue LED starts blinking. If you’re inside a building, it is very unlikely that you can get GPS data. Go outside or place your antenna outside to maximize your chances of catching a satellite signal.

Each line you get in the serial monitor is an NMEA sentence.

NMEA stands for National Marine Electronics Association, and in the world of GPS, it is a standard data format supported by GPS manufacturers.

NMEA Sentences

NMEA sentences start with the $ character, and each data field is separated by a comma.

$GNRMC,115209.00,A,4114.5500,N,00861.4900,W,0.129,,160125,,,D*XX
$GNVTG,,T,,M,0.129,N,0.239,K,D*XX
$GNGGA,115209.00,4114.5500,N,00861.4900,W,2,10,0.93,130.6,M,50.1,M,,0000*XX
$GNGSA,A,3,24,25,28,32,29,,,,,,,,1.65,0.93,1.37*XX
$GNGSA,A,3,78,66,67,77,,86,26,083,20*XX
$GLGSV,3,3,09,87,13,131,*XX
$GNGLL,4114.5500,N,00861.4900,W,115209.00,A,D*XX

There are different types of NMEA sentences. The type of message is indicated by the characters before the first comma.

The GN after the $ indicates it is a GPS position. The $GNGGA is the basic GNSS NMEA message, that provides 3D location and accuracy data.

In the following sentence:

$GNGGA,110827.00,4114.32485,N,00831.79799,W,1,10,0.93,130.6,M,50.1,M,,*5F

Here’s how the fields look for the M8N:

  • $GNGGA: Global GNSS location data.
  • 110827.00: Time in UTC (11:08:27).
  • 4114.32485,N: Latitude.
  • 00831.79799,W: Longitude.
  • 1: Fix quality (1 = GPS fix, 2 = DGPS, etc.).
  • 10: Number of satellites tracked (higher for M8N compared to NEO-6M).
  • 0.93: Horizontal dilution of precision (lower is better).
  • 130.6,M: Altitude above mean sea level (in meters).
  • 50.1,M: Height of geoid above the WGS84 ellipsoid.
  • *5F: Recalculated checksum for the NEO-M8N.

The other NMEA sentences provide additional information:

  • $GNRMC – Essential GNSS PVT (Position, Velocity, Time) data
  • $GNVTG – Velocity and track information
  • $GNGGA – GNSS Fix Information
  • $GNGSA – GNSS DOP and active satellites
  • $GLGSV – Detailed satellite information (GLONASS)
  • $GNGLL – Geographic Latitude and Longitude.

For more information about NMEA sentences, I found this website with very detailed information.

You can use this Online NME Analyser and paste your sentences there to interpret the GPS data.

However, the easiest way to get and interpret the GPS data you want is to parse your NMEA sentences directly in the code. For that, we’ll use the micropyGPS module.

Uploading the micropyGPS Module

To parse the NMEA sentences from the GPS module and get GPS data easily, we’ll use the micropyGPS module. This library isn’t part of the standard MicroPython library by default. So, you need to upload the following file to your Raspberry Pi Pico board (save it with the name micropyGPS.py).

"""
# MicropyGPS - a GPS NMEA sentence parser for Micropython/Python 3.X
# Copyright (c) 2017 Michael Calvin McCoy ([email protected])
# The MIT License (MIT) - see LICENSE file
"""

# TODO:
# Time Since First Fix
# Distance/Time to Target
# More Helper Functions
# Dynamically limit sentences types to parse

from math import floor, modf

# Import utime or time for fix time handling
try:
    # Assume running on MicroPython
    import utime
except ImportError:
    # Otherwise default to time module for non-embedded implementations
    # Should still support millisecond resolution.
    import time


class MicropyGPS(object):
    """GPS NMEA Sentence Parser. Creates object that stores all relevant GPS data and statistics.
    Parses sentences one character at a time using update(). """

    # Max Number of Characters a valid sentence can be (based on GGA sentence)
    SENTENCE_LIMIT = 90
    __HEMISPHERES = ('N', 'S', 'E', 'W')
    __NO_FIX = 1
    __FIX_2D = 2
    __FIX_3D = 3
    __DIRECTIONS = ('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W',
                    'WNW', 'NW', 'NNW')
    __MONTHS = ('January', 'February', 'March', 'April', 'May',
                'June', 'July', 'August', 'September', 'October',
                'November', 'December')

    def __init__(self, local_offset=0, location_formatting='ddm'):
        """
        Setup GPS Object Status Flags, Internal Data Registers, etc
            local_offset (int): Timzone Difference to UTC
            location_formatting (str): Style For Presenting Longitude/Latitude:
                                       Decimal Degree Minute (ddm) - 40° 26.767′ N
                                       Degrees Minutes Seconds (dms) - 40° 26′ 46″ N
                                       Decimal Degrees (dd) - 40.446° N
        """

        #####################
        # Object Status Flags
        self.sentence_active = False
        self.active_segment = 0
        self.process_crc = False
        self.gps_segments = []
        self.crc_xor = 0
        self.char_count = 0
        self.fix_time = 0

        #####################
        # Sentence Statistics
        self.crc_fails = 0
        self.clean_sentences = 0
        self.parsed_sentences = 0

        #####################
        # Logging Related
        self.log_handle = None
        self.log_en = False

        #####################
        # Data From Sentences
        # Time
        self.timestamp = [0, 0, 0.0]
        self.date = [0, 0, 0]
        self.local_offset = local_offset

        # Position/Motion
        self._latitude = [0, 0.0, 'N']
        self._longitude = [0, 0.0, 'W']
        self.coord_format = location_formatting
        self.speed = [0.0, 0.0, 0.0]
        self.course = 0.0
        self.altitude = 0.0
        self.geoid_height = 0.0

        # GPS Info
        self.satellites_in_view = 0
        self.satellites_in_use = 0
        self.satellites_used = []
        self.last_sv_sentence = 0
        self.total_sv_sentences = 0
        self.satellite_data = dict()
        self.hdop = 0.0
        self.pdop = 0.0
        self.vdop = 0.0
        self.valid = False
        self.fix_stat = 0
        self.fix_type = 1

    ########################################
    # Coordinates Translation Functions
    ########################################
    @property
    def latitude(self):
        """Format Latitude Data Correctly"""
        if self.coord_format == 'dd':
            decimal_degrees = self._latitude[0] + (self._latitude[1] / 60)
            return [decimal_degrees, self._latitude[2]]
        elif self.coord_format == 'dms':
            minute_parts = modf(self._latitude[1])
            seconds = round(minute_parts[0] * 60)
            return [self._latitude[0], int(minute_parts[1]), seconds, self._latitude[2]]
        else:
            return self._latitude

    @property
    def longitude(self):
        """Format Longitude Data Correctly"""
        if self.coord_format == 'dd':
            decimal_degrees = self._longitude[0] + (self._longitude[1] / 60)
            return [decimal_degrees, self._longitude[2]]
        elif self.coord_format == 'dms':
            minute_parts = modf(self._longitude[1])
            seconds = round(minute_parts[0] * 60)
            return [self._longitude[0], int(minute_parts[1]), seconds, self._longitude[2]]
        else:
            return self._longitude

    ########################################
    # Logging Related Functions
    ########################################
    def start_logging(self, target_file, mode="append"):
        """
        Create GPS data log object
        """
        # Set Write Mode Overwrite or Append
        mode_code = 'w' if mode == 'new' else 'a'

        try:
            self.log_handle = open(target_file, mode_code)
        except AttributeError:
            print("Invalid FileName")
            return False

        self.log_en = True
        return True

    def stop_logging(self):
        """
        Closes the log file handler and disables further logging
        """
        try:
            self.log_handle.close()
        except AttributeError:
            print("Invalid Handle")
            return False

        self.log_en = False
        return True

    def write_log(self, log_string):
        """Attempts to write the last valid NMEA sentence character to the active file handler
        """
        try:
            self.log_handle.write(log_string)
        except TypeError:
            return False
        return True

    ########################################
    # Sentence Parsers
    ########################################
    def gprmc(self):
        """Parse Recommended Minimum Specific GPS/Transit data (RMC)Sentence.
        Updates UTC timestamp, latitude, longitude, Course, Speed, Date, and fix status
        """

        # UTC Timestamp
        try:
            utc_string = self.gps_segments[1]

            if utc_string:  # Possible timestamp found
                hours = (int(utc_string[0:2]) + self.local_offset) % 24
                minutes = int(utc_string[2:4])
                seconds = float(utc_string[4:])
                self.timestamp = [hours, minutes, seconds]
            else:  # No Time stamp yet
                self.timestamp = [0, 0, 0.0]

        except ValueError:  # Bad Timestamp value present
            return False

        # Date stamp
        try:
            date_string = self.gps_segments[9]

            # Date string printer function assumes to be year >=2000,
            # date_string() must be supplied with the correct century argument to display correctly
            if date_string:  # Possible date stamp found
                day = int(date_string[0:2])
                month = int(date_string[2:4])
                year = int(date_string[4:6])
                self.date = (day, month, year)
            else:  # No Date stamp yet
                self.date = (0, 0, 0)

        except ValueError:  # Bad Date stamp value present
            return False

        # Check Receiver Data Valid Flag
        if self.gps_segments[2] == 'A':  # Data from Receiver is Valid/Has Fix

            # Longitude / Latitude
            try:
                # Latitude
                l_string = self.gps_segments[3]
                lat_degs = int(l_string[0:2])
                lat_mins = float(l_string[2:])
                lat_hemi = self.gps_segments[4]

                # Longitude
                l_string = self.gps_segments[5]
                lon_degs = int(l_string[0:3])
                lon_mins = float(l_string[3:])
                lon_hemi = self.gps_segments[6]
            except ValueError:
                return False

            if lat_hemi not in self.__HEMISPHERES:
                return False

            if lon_hemi not in self.__HEMISPHERES:
                return False

            # Speed
            try:
                spd_knt = float(self.gps_segments[7])
            except ValueError:
                return False

            # Course
            try:
                if self.gps_segments[8]:
                    course = float(self.gps_segments[8])
                else:
                    course = 0.0
            except ValueError:
                return False

            # TODO - Add Magnetic Variation

            # Update Object Data
            self._latitude = [lat_degs, lat_mins, lat_hemi]
            self._longitude = [lon_degs, lon_mins, lon_hemi]
            # Include mph and hm/h
            self.speed = [spd_knt, spd_knt * 1.151, spd_knt * 1.852]
            self.course = course
            self.valid = True

            # Update Last Fix Time
            self.new_fix_time()

        else:  # Clear Position Data if Sentence is 'Invalid'
            self._latitude = [0, 0.0, 'N']
            self._longitude = [0, 0.0, 'W']
            self.speed = [0.0, 0.0, 0.0]
            self.course = 0.0
            self.valid = False

        return True

    def gpgll(self):
        """Parse Geographic Latitude and Longitude (GLL)Sentence. Updates UTC timestamp, latitude,
        longitude, and fix status"""

        # UTC Timestamp
        try:
            utc_string = self.gps_segments[5]

            if utc_string:  # Possible timestamp found
                hours = (int(utc_string[0:2]) + self.local_offset) % 24
                minutes = int(utc_string[2:4])
                seconds = float(utc_string[4:])
                self.timestamp = [hours, minutes, seconds]
            else:  # No Time stamp yet
                self.timestamp = [0, 0, 0.0]

        except ValueError:  # Bad Timestamp value present
            return False

        # Check Receiver Data Valid Flag
        if self.gps_segments[6] == 'A':  # Data from Receiver is Valid/Has Fix

            # Longitude / Latitude
            try:
                # Latitude
                l_string = self.gps_segments[1]
                lat_degs = int(l_string[0:2])
                lat_mins = float(l_string[2:])
                lat_hemi = self.gps_segments[2]

                # Longitude
                l_string = self.gps_segments[3]
                lon_degs = int(l_string[0:3])
                lon_mins = float(l_string[3:])
                lon_hemi = self.gps_segments[4]
            except ValueError:
                return False

            if lat_hemi not in self.__HEMISPHERES:
                return False

            if lon_hemi not in self.__HEMISPHERES:
                return False

            # Update Object Data
            self._latitude = [lat_degs, lat_mins, lat_hemi]
            self._longitude = [lon_degs, lon_mins, lon_hemi]
            self.valid = True

            # Update Last Fix Time
            self.new_fix_time()

        else:  # Clear Position Data if Sentence is 'Invalid'
            self._latitude = [0, 0.0, 'N']
            self._longitude = [0, 0.0, 'W']
            self.valid = False

        return True

    def gpvtg(self):
        """Parse Track Made Good and Ground Speed (VTG) Sentence. Updates speed and course"""
        try:
            course = float(self.gps_segments[1]) if self.gps_segments[1] else 0.0
            spd_knt = float(self.gps_segments[5]) if self.gps_segments[5] else 0.0
        except ValueError:
            return False

        # Include mph and km/h
        self.speed = (spd_knt, spd_knt * 1.151, spd_knt * 1.852)
        self.course = course
        return True

    def gpgga(self):
        """Parse Global Positioning System Fix Data (GGA) Sentence. Updates UTC timestamp, latitude, longitude,
        fix status, satellites in use, Horizontal Dilution of Precision (HDOP), altitude, geoid height and fix status"""

        try:
            # UTC Timestamp
            utc_string = self.gps_segments[1]

            # Skip timestamp if receiver doesn't have on yet
            if utc_string:
                hours = (int(utc_string[0:2]) + self.local_offset) % 24
                minutes = int(utc_string[2:4])
                seconds = float(utc_string[4:])
            else:
                hours = 0
                minutes = 0
                seconds = 0.0

            # Number of Satellites in Use
            satellites_in_use = int(self.gps_segments[7])

            # Get Fix Status
            fix_stat = int(self.gps_segments[6])

        except (ValueError, IndexError):
            return False

        try:
            # Horizontal Dilution of Precision
            hdop = float(self.gps_segments[8])
        except (ValueError, IndexError):
            hdop = 0.0

        # Process Location and Speed Data if Fix is GOOD
        if fix_stat:

            # Longitude / Latitude
            try:
                # Latitude
                l_string = self.gps_segments[2]
                lat_degs = int(l_string[0:2])
                lat_mins = float(l_string[2:])
                lat_hemi = self.gps_segments[3]

                # Longitude
                l_string = self.gps_segments[4]
                lon_degs = int(l_string[0:3])
                lon_mins = float(l_string[3:])
                lon_hemi = self.gps_segments[5]
            except ValueError:
                return False

            if lat_hemi not in self.__HEMISPHERES:
                return False

            if lon_hemi not in self.__HEMISPHERES:
                return False

            # Altitude / Height Above Geoid
            try:
                altitude = float(self.gps_segments[9])
                geoid_height = float(self.gps_segments[11])
            except ValueError:
                altitude = 0
                geoid_height = 0

            # Update Object Data
            self._latitude = [lat_degs, lat_mins, lat_hemi]
            self._longitude = [lon_degs, lon_mins, lon_hemi]
            self.altitude = altitude
            self.geoid_height = geoid_height

        # Update Object Data
        self.timestamp = [hours, minutes, seconds]
        self.satellites_in_use = satellites_in_use
        self.hdop = hdop
        self.fix_stat = fix_stat

        # If Fix is GOOD, update fix timestamp
        if fix_stat:
            self.new_fix_time()

        return True

    def gpgsa(self):
        """Parse GNSS DOP and Active Satellites (GSA) sentence. Updates GPS fix type, list of satellites used in
        fix calculation, Position Dilution of Precision (PDOP), Horizontal Dilution of Precision (HDOP), Vertical
        Dilution of Precision, and fix status"""

        # Fix Type (None,2D or 3D)
        try:
            fix_type = int(self.gps_segments[2])
        except ValueError:
            return False

        # Read All (up to 12) Available PRN Satellite Numbers
        sats_used = []
        for sats in range(12):
            sat_number_str = self.gps_segments[3 + sats]
            if sat_number_str:
                try:
                    sat_number = int(sat_number_str)
                    sats_used.append(sat_number)
                except ValueError:
                    return False
            else:
                break

        # PDOP,HDOP,VDOP
        try:
            pdop = float(self.gps_segments[15])
            hdop = float(self.gps_segments[16])
            vdop = float(self.gps_segments[17])
        except ValueError:
            return False

        # Update Object Data
        self.fix_type = fix_type

        # If Fix is GOOD, update fix timestamp
        if fix_type > self.__NO_FIX:
            self.new_fix_time()

        self.satellites_used = sats_used
        self.hdop = hdop
        self.vdop = vdop
        self.pdop = pdop

        return True

    def gpgsv(self):
        """Parse Satellites in View (GSV) sentence. Updates number of SV Sentences,the number of the last SV sentence
        parsed, and data on each satellite present in the sentence"""
        try:
            num_sv_sentences = int(self.gps_segments[1])
            current_sv_sentence = int(self.gps_segments[2])
            sats_in_view = int(self.gps_segments[3])
        except ValueError:
            return False

        # Create a blank dict to store all the satellite data from this sentence in:
        # satellite PRN is key, tuple containing telemetry is value
        satellite_dict = dict()

        # Calculate  Number of Satelites to pull data for and thus how many segment positions to read
        if num_sv_sentences == current_sv_sentence:
            # Last sentence may have 1-4 satellites; 5 - 20 positions
            sat_segment_limit = (sats_in_view - ((num_sv_sentences - 1) * 4)) * 5
        else:
            sat_segment_limit = 20  # Non-last sentences have 4 satellites and thus read up to position 20

        # Try to recover data for up to 4 satellites in sentence
        for sats in range(4, sat_segment_limit, 4):

            # If a PRN is present, grab satellite data
            if self.gps_segments[sats]:
                try:
                    sat_id = int(self.gps_segments[sats])
                except (ValueError,IndexError):
                    return False

                try:  # elevation can be null (no value) when not tracking
                    elevation = int(self.gps_segments[sats+1])
                except (ValueError,IndexError):
                    elevation = None

                try:  # azimuth can be null (no value) when not tracking
                    azimuth = int(self.gps_segments[sats+2])
                except (ValueError,IndexError):
                    azimuth = None

                try:  # SNR can be null (no value) when not tracking
                    snr = int(self.gps_segments[sats+3])
                except (ValueError,IndexError):
                    snr = None
            # If no PRN is found, then the sentence has no more satellites to read
            else:
                break

            # Add Satellite Data to Sentence Dict
            satellite_dict[sat_id] = (elevation, azimuth, snr)

        # Update Object Data
        self.total_sv_sentences = num_sv_sentences
        self.last_sv_sentence = current_sv_sentence
        self.satellites_in_view = sats_in_view

        # For a new set of sentences, we either clear out the existing sat data or
        # update it as additional SV sentences are parsed
        if current_sv_sentence == 1:
            self.satellite_data = satellite_dict
        else:
            self.satellite_data.update(satellite_dict)

        return True

    ##########################################
    # Data Stream Handler Functions
    ##########################################

    def new_sentence(self):
        """Adjust Object Flags in Preparation for a New Sentence"""
        self.gps_segments = ['']
        self.active_segment = 0
        self.crc_xor = 0
        self.sentence_active = True
        self.process_crc = True
        self.char_count = 0

    def update(self, new_char):
        """Process a new input char and updates GPS object if necessary based on special characters ('$', ',', '*')
        Function builds a list of received string that are validate by CRC prior to parsing by the  appropriate
        sentence function. Returns sentence type on successful parse, None otherwise"""

        valid_sentence = False

        # Validate new_char is a printable char
        ascii_char = ord(new_char)

        if 10 <= ascii_char <= 126:
            self.char_count += 1

            # Write Character to log file if enabled
            if self.log_en:
                self.write_log(new_char)

            # Check if a new string is starting ($)
            if new_char == '$':
                self.new_sentence()
                return None

            elif self.sentence_active:

                # Check if sentence is ending (*)
                if new_char == '*':
                    self.process_crc = False
                    self.active_segment += 1
                    self.gps_segments.append('')
                    return None

                # Check if a section is ended (,), Create a new substring to feed
                # characters to
                elif new_char == ',':
                    self.active_segment += 1
                    self.gps_segments.append('')

                # Store All Other printable character and check CRC when ready
                else:
                    self.gps_segments[self.active_segment] += new_char

                    # When CRC input is disabled, sentence is nearly complete
                    if not self.process_crc:

                        if len(self.gps_segments[self.active_segment]) == 2:
                            try:
                                final_crc = int(self.gps_segments[self.active_segment], 16)
                                if self.crc_xor == final_crc:
                                    valid_sentence = True
                                else:
                                    self.crc_fails += 1
                            except ValueError:
                                pass  # CRC Value was deformed and could not have been correct

                # Update CRC
                if self.process_crc:
                    self.crc_xor ^= ascii_char

                # If a Valid Sentence Was received and it's a supported sentence, then parse it!!
                if valid_sentence:
                    self.clean_sentences += 1  # Increment clean sentences received
                    self.sentence_active = False  # Clear Active Processing Flag

                    if self.gps_segments[0] in self.supported_sentences:

                        # parse the Sentence Based on the message type, return True if parse is clean
                        if self.supported_sentences[self.gps_segments[0]](self):

                            # Let host know that the GPS object was updated by returning parsed sentence type
                            self.parsed_sentences += 1
                            return self.gps_segments[0]

                # Check that the sentence buffer isn't filling up with Garage waiting for the sentence to complete
                if self.char_count > self.SENTENCE_LIMIT:
                    self.sentence_active = False

        # Tell Host no new sentence was parsed
        return None

    def new_fix_time(self):
        """Updates a high resolution counter with current time when fix is updated. Currently only triggered from
        GGA, GSA and RMC sentences"""
        try:
            self.fix_time = utime.ticks_ms()
        except NameError:
            self.fix_time = time.time()

    #########################################
    # User Helper Functions
    # These functions make working with the GPS object data easier
    #########################################

    def satellite_data_updated(self):
        """
        Checks if the all the GSV sentences in a group have been read, making satellite data complete
        :return: boolean
        """
        if self.total_sv_sentences > 0 and self.total_sv_sentences == self.last_sv_sentence:
            return True
        else:
            return False

    def unset_satellite_data_updated(self):
        """
        Mark GSV sentences as read indicating the data has been used and future updates are fresh
        """
        self.last_sv_sentence = 0

    def satellites_visible(self):
        """
        Returns a list of of the satellite PRNs currently visible to the receiver
        :return: list
        """
        return list(self.satellite_data.keys())

    def time_since_fix(self):
        """Returns number of millisecond since the last sentence with a valid fix was parsed. Returns 0 if
        no fix has been found"""

        # Test if a Fix has been found
        if self.fix_time == 0:
            return -1

        # Try calculating fix time using utime; if not running MicroPython
        # time.time() returns a floating point value in secs
        try:
            current = utime.ticks_diff(utime.ticks_ms(), self.fix_time)
        except NameError:
            current = (time.time() - self.fix_time) * 1000  # ms

        return current

    def compass_direction(self):
        """
        Determine a cardinal or inter-cardinal direction based on current course.
        :return: string
        """
        # Calculate the offset for a rotated compass
        if self.course >= 348.75:
            offset_course = 360 - self.course
        else:
            offset_course = self.course + 11.25

        # Each compass point is separated by 22.5 degrees, divide to find lookup value
        dir_index = floor(offset_course / 22.5)

        final_dir = self.__DIRECTIONS[dir_index]

        return final_dir

    def latitude_string(self):
        """
        Create a readable string of the current latitude data
        :return: string
        """
        if self.coord_format == 'dd':
            formatted_latitude = self.latitude
            lat_string = str(formatted_latitude[0]) + '° ' + str(self._latitude[2])
        elif self.coord_format == 'dms':
            formatted_latitude = self.latitude
            lat_string = str(formatted_latitude[0]) + '° ' + str(formatted_latitude[1]) + "' " + str(formatted_latitude[2]) + '" ' + str(formatted_latitude[3])
        else:
            lat_string = str(self._latitude[0]) + '° ' + str(self._latitude[1]) + "' " + str(self._latitude[2])
        return lat_string

    def longitude_string(self):
        """
        Create a readable string of the current longitude data
        :return: string
        """
        if self.coord_format == 'dd':
            formatted_longitude = self.longitude
            lon_string = str(formatted_longitude[0]) + '° ' + str(self._longitude[2])
        elif self.coord_format == 'dms':
            formatted_longitude = self.longitude
            lon_string = str(formatted_longitude[0]) + '° ' + str(formatted_longitude[1]) + "' " + str(formatted_longitude[2]) + '" ' + str(formatted_longitude[3])
        else:
            lon_string = str(self._longitude[0]) + '° ' + str(self._longitude[1]) + "' " + str(self._longitude[2])
        return lon_string

    def speed_string(self, unit='kph'):
        """
        Creates a readable string of the current speed data in one of three units
        :param unit: string of 'kph','mph, or 'knot'
        :return:
        """
        if unit == 'mph':
            speed_string = str(self.speed[1]) + ' mph'

        elif unit == 'knot':
            if self.speed[0] == 1:
                unit_str = ' knot'
            else:
                unit_str = ' knots'
            speed_string = str(self.speed[0]) + unit_str

        else:
            speed_string = str(self.speed[2]) + ' km/h'

        return speed_string

    def date_string(self, formatting='s_mdy', century='20'):
        """
        Creates a readable string of the current date.
        Can select between long format: Januray 1st, 2014
        or two short formats:
        11/01/2014 (MM/DD/YYYY)
        01/11/2014 (DD/MM/YYYY)
        :param formatting: string 's_mdy', 's_dmy', or 'long'
        :param century: int delineating the century the GPS data is from (19 for 19XX, 20 for 20XX)
        :return: date_string  string with long or short format date
        """

        # Long Format Januray 1st, 2014
        if formatting == 'long':
            # Retrieve Month string from private set
            month = self.__MONTHS[self.date[1] - 1]

            # Determine Date Suffix
            if self.date[0] in (1, 21, 31):
                suffix = 'st'
            elif self.date[0] in (2, 22):
                suffix = 'nd'
            elif self.date[0] == (3, 23):
                suffix = 'rd'
            else:
                suffix = 'th'

            day = str(self.date[0]) + suffix  # Create Day String

            year = century + str(self.date[2])  # Create Year String

            date_string = month + ' ' + day + ', ' + year  # Put it all together

        else:
            # Add leading zeros to day string if necessary
            if self.date[0] < 10:
                day = '0' + str(self.date[0])
            else:
                day = str(self.date[0])

            # Add leading zeros to month string if necessary
            if self.date[1] < 10:
                month = '0' + str(self.date[1])
            else:
                month = str(self.date[1])

            # Add leading zeros to year string if necessary
            if self.date[2] < 10:
                year = '0' + str(self.date[2])
            else:
                year = str(self.date[2])

            # Build final string based on desired formatting
            if formatting == 's_dmy':
                date_string = day + '/' + month + '/' + year

            else:  # Default date format
                date_string = month + '/' + day + '/' + year

        return date_string

    # All the currently supported NMEA sentences
    supported_sentences = {'GPRMC': gprmc, 'GLRMC': gprmc,
                           'GPGGA': gpgga, 'GLGGA': gpgga,
                           'GPVTG': gpvtg, 'GLVTG': gpvtg,
                           'GPGSA': gpgsa, 'GLGSA': gpgsa,
                           'GPGSV': gpgsv, 'GLGSV': gpgsv,
                           'GPGLL': gpgll, 'GLGLL': gpgll,
                           'GNGGA': gpgga, 'GNRMC': gprmc,
                           'GNVTG': gpvtg, 'GNGLL': gpgll,
                           'GNGSA': gpgsa,
                          }

if __name__ == "__main__":
    pass

View raw code

These are the general instructions to upload the micropyGPS library to your board:

  1. First, make sure your board is running MicroPython firmware—check the Prerequisites section.
  2. Create a new file in your IDE with the name micropyGPS.py and paste the previous code there. Save that file.
  3. Establish a serial communication with your board using your IDE.
  4. Upload the micropyGPS.py file to your board. In Thonny IDE, go to File > Save as… and select MicroPython Device/Raspberry Pi Pico.
  5. At this point, the library should have been successfully uploaded to your board. Now, you can use the library functionalities in your code by importing the library import micropyGPS.

Raspberry Pi Pico with NEO-M8N: Getting GPS Data with MicroPython

The micropyGPS library makes it easier to get GPS data in a format that is easy to understand.

The following code shows how to use the library to get GPS data like latitude, longitude, altitude, date and time, number of visible satellites and HDOP (a measurement of how precise the signal is).

After importing the micropyGPS library to your board, you can run the following code.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-neo-m8n-gps-micropytho

from machine import UART, Pin
from time import sleep
from micropyGPS import MicropyGPS

# Instantiate the micropyGPS object
my_gps = MicropyGPS()

# Define the UART pins and create a UART object
gps_serial = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))

while True:
    try:
        while gps_serial.any():
            data = gps_serial.read()
            for byte in data:
                stat = my_gps.update(chr(byte))
                if stat is not None:
                    # Print parsed GPS data
                    print('UTC Timestamp:', my_gps.timestamp)
                    print('Date:', my_gps.date_string('long'))
                    print('Latitude:', my_gps.latitude_string())
                    print('Longitude:', my_gps.longitude_string())
                    print('Altitude:', my_gps.altitude)
                    print('Satellites in use:', my_gps.satellites_in_use)
                    print('Horizontal Dilution of Precision:', my_gps.hdop)
                    print()
                    number = my_gps.latitude
                    print(number)
    except Exception as e:
        print(f"An error occurred: {e}")

View raw code

How Does the Code Work?

Continue reading to learn how the code works, or skip to the demonstration section.

First, import the required modules, including the MicropyGPS class from the micropyGPS module you imported previously.

from machine import UART, Pin
from time import sleep
from micropyGPS import MicropyGPS

Create an instance of the MicropyGPS class called my_gps.

# Instantiate the micropyGPS object
my_gps = MicropyGPS()

Then, initialize a UART instance for serial communication with the module. We’re using UART 1 and GPIO 4 for TX and GPIO 5 for RX. We also define the baud rate for the GPS module (the NEO-M8N uses 9600).

gps_serial = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))

Then, we create an infinite loop to continuously read GPS data.

We check if there is new data available to read. If there is, we read the data and pass it to the my_gps instance using the update() method.

while gps_serial.any():
    data = gps_serial.read()
    for byte in data:
        stat = my_gps.update(chr(byte))

The update() method returns valid GPS sentences or None if that’s not the case. So, we check if we have valid data before proceeding.

if stat is not None:

Then, we can access the GPS data by using the micropyGPS methods on the my_gps object that should contain the data gathered from the GPS module.

The following lines show how to get time, date, latitude, longitude, altitude, number of satellites used, and HDOP.

# Print parsed GPS data
print('UTC Timestamp:', my_gps.timestamp)
print('Date:', my_gps.date_string('long'))
print('Latitude:', my_gps.latitude_string())
print('Longitude:', my_gps.longitude_string())
print('Altitude:', my_gps.altitude)
print('Satellites in use:', my_gps.satellites_in_use)
print('Horizontal Dilution of Precision:', my_gps.hdop)
print()

The micropyGPS library supports other methods to get more GPS data and in different formats. We recommend you take a look at the documentation and see all the available options.

Demonstration

After uploading the micropyGPS module to your board, you can run this previous code to get GPS data.

Run code Thonny IDE

Make sure you place your board or antenna next to a window, or preferably outside so that it can get data from satellites. You may need to wait a few minutes until it gets a position fix and can send valid data. The NEO-M8N GPS module’s blue LED will start blinking when it’s ready.

In the MicroPython shell, you should get information about your current location, date and time in UTC, number of satellites, and HDOP. The higher the number of satellites and the lower the HDO the better.

Raspberry Pi Pico with NEO-M8N Get GPS data with MicroPython Demonstration

GPS Logger and Display Path on Google Earth

Now that you’re more familiar with using the NEO-M8N GPS module with the Raspberry Pi Pico, let’s create a GPS logger that records your location over time to a file on a microSD card. Then, you can modify and use that file on Google Earth to visualize how the location changed over time (path).

Recommended reading: Raspberry Pi Pico: MicroSD Card Guide with Datalogging Example (MicroPython).

GPS Logger and Display Path on Google Earth - RPi Pico and NEO-M8N

Project Overview

Here’s a quick overview of how this project works:

  • The Raspberry Pi Pico is connected to the NEO-M8N GPS Module and gets data about the location;
  • Every three seconds, we save the location data (latitude, longitude, and altitude) to a file on the microSD card;
  • To visualize the data on Google Earth, we’ll show you how to manually convert a .txt file with the location coordinates to a .kml file that Google Earth can read;
  • We’ll show you how to upload the .kml to Google Earth to visualize that path.

Parts Required

Here’s a list of the parts required for this project:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Wiring the Circuit

Wire the GPS Module to the Pico UART pins (as we did previously) and the microSD card module to SPI pins of your choice. We’ll use the pins shown in the following schematic diagram and tables – use those as a reference.

Recommended reading: Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained.

Raspberry Pi Pico GPS logger with NEO-M8N and microSD card
NEO-6M GPS ModuleRaspberry Pi Pico
VCC3V3(OUT) (Pin 36)
RXTX (GPIO 4) (Pin 6)
TXRX (GPIO 5) (Pin 7)
GNDGND
microSD Card ModuleRaspberry Pi Pico
3V3*3V3(OUT) (Pin 36)
CSGPIO 17 (Pin 22)
MOSIGPIO 19 (Pin 25)
CLKGPIO 18 (Pin 24)
MISOGPIO 16 (Pin 21)
GNDGND
* some microSD card modules require 5V instead of 3V3. If that’s the case, connect the VCC of the microSD card to the VBUS pin.

Importing the sdcard.py Module

At the moment, there isn’t much support in terms of libraries to use the microSD card with the Raspberry Pi Pico. We’ve found the sdcard.py module that seems to work just fine to handle files on the microSD card. Follow the next steps to install the library.

  1. Click here to download the sdcard.py library code.
  2. Create a new file in Thonny IDE and copy the library code.
  3. Go to File > Save as and select Raspberry Pi Pico.
  4. Name the file sdcard.py and click OK to save the file on the Raspberry Pi Pico.

And that’s it. The library was uploaded to your board. Now, you can use the library functionalities in your code by importing the library.

Testing the MicroSD Card

Upload the following code to your Raspberry Pi Pico to check if it can communicate with the microSD card.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-neo-m8n-gps-micropytho

from machine import SPI, Pin
import sdcard, os

# Constants
SPI_BUS = 0
SCK_PIN = 18
MOSI_PIN = 19
MISO_PIN = 16
CS_PIN = 17
SD_MOUNT_PATH = '/sd'

try:
    # Init SPI communication
    spi = SPI(SPI_BUS,sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))
    cs = Pin(CS_PIN)
    sd = sdcard.SDCard(spi, cs)
    # Mount microSD card
    os.mount(sd, SD_MOUNT_PATH)
    # List files on the microSD card
    print(os.listdir(SD_MOUNT_PATH))
    
except Exception as e:
    print('An error occurred:', e)

View raw code

The previous code starts SPI communication on the pins that the microSD card is connected to, tries to mount the microSD card, and then, tries to list the files there.

If you’re using different SPI pins, you should modify the code accordingly. Also notice that depending on the pins used, you might need to change the SPI bus. On the Raspberry Pi Pico pinout, you can see which pins are on SPI bus 1 or 0.

SPI_BUS = 0
SCK_PIN = 18
MOSI_PIN = 19
MISO_PIN = 16
CS_PIN = 17

Run the previous code on your Raspberry Pi Pico by clicking on the Thonny IDE run green button.

Run code in Thonny IDE

You should get a similar message on the Shell (see the screenshot below). If that’s the case, it means everything is working as expected. If not, check the wiring, if the microSD card is properly inserted, and if you’re using the right SPI Bus number for the pins you’re using.

microsd card mount successfully Thonny IDE RPI Pico - Testing

If everything is working as expected, you can now test the code to log GPS data to the microSD card.

Log GPS Data to the microSD Card – Code

The following code initializes the microSD card and the GPS module and saves GPS data as soon as the data points are available every three seconds (you can change the delay time).

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-neo-m8n-gps-micropytho

from machine import UART, Pin, Timer, SPI
from time import sleep, ticks_ms, ticks_diff
from micropyGPS import MicropyGPS
import sdcard, os

# microSD card pin definition
SPI_BUS = 0
SCK_PIN = 18
MOSI_PIN = 19
MISO_PIN = 16
CS_PIN = 17

# microSD card filesystem mount path
SD_MOUNT_PATH = '/sd'
# file path to save data
FILE_PATH = '/sd/data.txt'

# Init SPI communication for the microSD card
spi = SPI(SPI_BUS, sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))
cs = Pin(CS_PIN)

# Instantiate the micropyGPS object
my_gps = MicropyGPS()

# Define the UART pins and create a UART object
gps_serial = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))

def mount_sdcard(spi, cs_pin):
    try:
        sd = sdcard.SDCard(spi, cs_pin)
        # Mount microSD card
        os.mount(sd, SD_MOUNT_PATH)
        # List files on the microSD card
        print(os.listdir(SD_MOUNT_PATH))
    
    except Exception as e:
        print('An error occurred mounting the SD card:', e)
        
def write_to_sd(data, file_path):
    try:
        # Open the file in append mode ('a')
        with open(file_path, 'a') as file:
            file.write(data + '\n')
        print("Data logged successfully.")
    except Exception as e:
        print(f"An error occurred while writing to SD card: {e}")

# Convert Longitude and Latitude to decimal degrees
def convert_to_decimal_degrees(coord):
    degrees = coord[0]
    minutes = coord[1]
    hemisphere = coord[2]
    
    decimal_degrees = degrees + (minutes / 60)
    
    # Make the value negative if it's in the western or southern hemisphere
    if hemisphere in ['S', 'W']:
        decimal_degrees *= -1
    
    return decimal_degrees

# Mount SD card
mount_sdcard(spi, cs)

# Initialize a timer variable
last_print_time = ticks_ms()  # Get the current time in milliseconds

while True:
    try:
        # Check if data is available in the UART buffer
        while gps_serial.any():
            data = gps_serial.read()
            for byte in data:
                stat = my_gps.update(chr(byte))
                if stat is not None:
                    # Check if 3 seconds have passed since the last print
                    current_time = ticks_ms()
                    if ticks_diff(current_time, last_print_time) >= 3000:
                        # Get longitude, latitude, and altitude
                        longitude = convert_to_decimal_degrees(my_gps.longitude)
                        latitude = convert_to_decimal_degrees(my_gps.latitude)
                        altitude = my_gps.altitude
                        GPS_data = f"{longitude},{latitude},{altitude}"
                        
                        # Print the GPS data
                        print(GPS_data)
                        print()
                        
                        # Save data on the microSD card
                        write_to_sd(GPS_data, FILE_PATH);
                        
                        # Update the last print time
                        last_print_time = current_time
            
    except Exception as e:
        print(f"An error occurred: {e}")

View raw code

To save data in a format that Google Earth can read, we need to save longitude, latitude, and altitude in this order separated by commas (the latitude and longitude need to be in decimal degrees format). That’s what we do in this example. Later, we need to convert that information to a .kml file.

How Does the Code Work?

Start by importing the required modules and classes.

from machine import UART, Pin, Timer, SPI
from time import sleep, ticks_ms, ticks_diff
from micropyGPS import MicropyGPS
import sdcard, os

Define the pins you’re using to interface with the microSD card.

# microSD card pin definition
SPI_BUS = 0
SCK_PIN = 18
MOSI_PIN = 19
MISO_PIN = 16
CS_PIN = 17

Create variables to save the microSD card filesystem mount path and the file path where you’ll save the data. In our case, in a file called data.txt.

# microSD card filesystem mount path
SD_MOUNT_PATH = '/sd'
# file path to save data
FILE_PATH = '/sd/data.txt'

Initialize the SPI communication for the microSD card.

# Init SPI communication for the microSD card
spi = SPI(SPI_BUS, sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))
cs = Pin(CS_PIN)

Initialize the micropyGPS object. We’re calling it my_gps.

# Instantiate the micropyGPS object
my_gps = MicropyGPS()

Create a new UART object on the pins that will be used to interface with the microSD card.

# Define the UART pins and create a UART object
gps_serial = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))

The following function initializes and mounts the microSD card on the spi bus and cs pin defined earlier.

def mount_sdcard(spi, cs_pin):
    try:
        sd = sdcard.SDCard(spi, cs_pin)
        # Mount microSD card
        os.mount(sd, SD_MOUNT_PATH)
        # List files on the microSD card
        print(os.listdir(SD_MOUNT_PATH))
    
    except Exception as e:
        print('An error occurred mounting the SD card:', e)

The write_to_sd() function appends data to a file on the microSD card. The first argument is the string that you want to save to the file, and the second argument is the file path. This function will append data to a file if it already exists, or it will create it if it doesn’t exist yet.

def write_to_sd(data, file_path):
    try:
        # Open the file in append mode ('a')
        with open(file_path, 'a') as file:
            file.write(data + '\n')
        print("Data logged successfully.")
    except Exception as e:
        print(f"An error occurred while writing to SD card: {e}")

The following function converts the latitude and longitude data in the format obtained from the micropyGPS library to decimal degrees (the format used by .kml files).

# Convert Longitude and Latitude to decimal degrees
def convert_to_decimal_degrees(coord):
    degrees = coord[0]
    minutes = coord[1]
    hemisphere = coord[2]
    
    decimal_degrees = degrees + (minutes / 60)
    
    # Make the value negative if it's in the western or southern hemisphere
    if hemisphere in ['S', 'W']:
        decimal_degrees *= -1
    
    return decimal_degrees

After all variables and functions definitions, call the mount_sdcard() function to initialize and mount the microSD card.

mount_sdcard(spi, cs)

Then, create a variable that will save how many milliseconds have passed since the program started running (this variable will be used to check how long has passed since the last time we recorded a reading).

last_print_time = ticks_ms()  # Get the current time in milliseconds

Then, we create an infinite loop to continuously read and log GPS data.

while True:
    try:

We check if there is new data available to read. If there is, we read the data and pass it to the my_gps instance using the update() method.

while gps_serial.any():
    data = gps_serial.read()
    for byte in data:
        stat = my_gps.update(chr(byte))

The update() method returns valid GPS sentences or None if that’s not the case. So, we check if we have valid data before proceeding.

if stat is not None:

Then, we can access the GPS data by using the micropyGPS methods on the my_gps object that should contain the data gathered from the GPS module.

We check if three seconds have passed since the last time we logged the GPS data and we get the current longitude, latitude, and altitude. We convert the longitude and latitude to decimal degrees.

if ticks_diff(current_time, last_print_time) >= 3000:
    # Get longitude, latitude, and altitude
    longitude = convert_to_decimal_degrees(my_gps.longitude)
    latitude = convert_to_decimal_degrees(my_gps.latitude)
    altitude = my_gps.altitude

Then, we concatenate the longitude, latitude, and altitude in a string separated by commas.

GPS_data = f"{longitude},{latitude},{altitude}"

We print that data on the shell.

print(GPS_data)

Finally, we write that data to the microSD card by calling the write_to_sd() function we create earlier and passing as arguments the GPS_data and FILE_PATH.

write_to_sd(GPS_data, FILE_PATH);

In the end, we update the last_print_time variable to the current time.

last_print_time = current_time

Testing the Project

After importing all the required libraries, you can run the code on the Raspberry Pi Pico to test it. Make sure the module or antenna is located outside or close to a window so that it can get data from the satellites.

You should get something similar in the Shell:

RPi Pico Log GPS Data to a microSD card

Uploading the Code to the Raspberry Pi Pico

Important note: just running the file with Thonny IDE doesn’t copy it permanently to the board’s filesystem. This means that if you unplug it from your computer and apply power to the Pico board, nothing will happen because it doesn’t have any Python files saved on its filesystem. The Thonny IDE Run function is useful to test the code, but if you want to upload it permanently to your board, you need to create and save a file to the board filesystem. If you want to disconnect the Pico from your computer and go for a walk with it to record the GPS data to create a path, you need to upload the code to the board. Follow the next steps:

1) Stop the execution of the previous program by clicking on the Stop button if you haven’t already.

2) With the code copied to Thony IDE, go to File > Save as... Then, select Raspberry Pi Pico.

Save Files to Raspberry Pi Pico Thonny IDE

3) Save the file with the following name: main.py.

Note: When you name a file main.py, the Raspberry Pi Pico will run that file automatically on boot. If you call it a different name, it will still be saved on the board filesystem, but it will not run automatically on boot.

4) Finally, click OK to proceed.

Now, you can disconnect the RPi Pico from the computer and power it using a portable power source like a battery or portable charger.

Go for a walk with your circuit so that it starts recording your coordinates over time and you can obtain a considerable amount of points to design a path.

After recording some data, disconnect the microSD card from the module and connect it to your computer. The microSD card should have a data.txt file with the coordinates of your path.

For you to upload that data to Google Earth and design a path, we need to convert that file to .kml format.

KML Files

KML is a file format used to display geographic data in an Earth browser such as Google Earth. KML uses a tag-based structure with nested elements and attributes and is based on the XML standard. We won’t go into detail about the structure of this file. If you want to learn more you can check this tutorial about KML files by Google.

Converting your data.txt file to .kml format

1) Open the data.txt file with the GPS data gathered from the GPS module.

2) Edit your file so that your coordinates are between the <coordinates></coordinates> tags as follows:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Style id="yellowPoly">
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Placemark><styleUrl>#yellowPoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tesselate>1</tesselate>
<altitudeMode>absolute</altitudeMode>
<coordinates>
YOUR COORDINATES GO HERE
</coordinates>
</LineString></Placemark>
</Document></kml>

3) Save that file.

4) Edit its name from data.txt to data.kml. You’ll receive a warning about changing the file format. Accept it. Now, the file should be usable to upload to Google Earth.

Display the Path on Google Earth

Now, follow the next steps to display and visualize your path on Google Earth.

1) Go to the Google Earth Website.

2) Create a new project and give it a name.

Google Earth - Create Project

3) Go to File > Import File to Project > Upload from device.

4) Select the .kml file created previously.

5) Your path will be displayed on Google Earth with a yellow outline.

Rpi Pico with NEO-M8N GPS Logger - Display path on Google Earth

And that’s it! You learned how to log GPS data to a file on a microSD card and how to use that data to display a path on Google Earth.

Wrapping Up

In this guide, you learned how to use the NEO-M8N GPS Module with the Raspberry Pi Pico to get data about location, time, and more. We’ve shown you how to get raw GPS data and how to parse data.

Finally, we created a project to save the location data to a file on a microSD card. You learned how to convert the data to a format that Google Earth can read to design and display a path.

We hope you’ve found this guide useful. We have guides for other modules that you may find useful:

To learn more about the Raspberry Pi Pico, take a look at our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.