Bird
0
0
Raspberry Piprogramming~5 mins

GPS module data reading in Raspberry Pi

Choose your learning style9 modes available
Introduction

We read GPS module data to know the exact location and time. This helps in navigation and tracking.

When you want to find your current position on a map.
When building a device that tracks movement or routes.
When you need accurate time from satellites.
When creating a project that logs travel paths.
When you want to trigger actions based on location.
Syntax
Raspberry Pi
import serial
import time

# Open serial port to GPS module
ser = serial.Serial('/dev/serial0', 9600, timeout=1)

while True:
    line = ser.readline().decode('ascii', errors='replace')
    if line.startswith('$GPGGA'):
        print(line.strip())

Use the correct serial port for your GPS module (e.g., '/dev/serial0').

GPS data comes in NMEA sentences, starting with $ and a code like $GPGGA.

Examples
Read one line of raw GPS data and print it.
Raspberry Pi
import serial

ser = serial.Serial('/dev/serial0', 9600, timeout=1)
line = ser.readline().decode('ascii', errors='replace')
print(line)
Filter and print only the $GPRMC sentences which contain recommended minimum GPS data.
Raspberry Pi
import serial

ser = serial.Serial('/dev/serial0', 9600, timeout=1)

while True:
    line = ser.readline().decode('ascii', errors='replace')
    if line.startswith('$GPRMC'):
        print('RMC sentence:', line.strip())
Sample Program

This program reads GPS data continuously from the GPS module connected to the Raspberry Pi. It prints only the $GPGGA sentences, which include position and fix data. You can stop it anytime with Ctrl+C.

Raspberry Pi
import serial
import time

# Open serial port to GPS module
ser = serial.Serial('/dev/serial0', 9600, timeout=1)

print('Reading GPS data... Press Ctrl+C to stop.')

try:
    while True:
        line = ser.readline().decode('ascii', errors='replace')
        if line.startswith('$GPGGA'):
            print('GPS GGA data:', line.strip())
        time.sleep(1)
except KeyboardInterrupt:
    print('Stopped reading GPS data.')
    ser.close()
OutputSuccess
Important Notes

Make sure your GPS module is connected to the correct serial pins on the Raspberry Pi.

GPS modules send data in NMEA format, which you can parse for useful info like latitude and longitude.

Sometimes GPS data may be empty or incomplete if the module has no satellite fix yet.

Summary

GPS modules send location data over serial connection in NMEA sentences.

Use Python's serial library to read and decode this data on Raspberry Pi.

Filter sentences like $GPGGA or $GPRMC to get useful GPS info.