Skip to content

Instantly share code, notes, and snippets.

@shriyanss
Created December 27, 2024 14:58
Show Gist options
  • Select an option

  • Save shriyanss/2cc7db449ae3ba12b08f6b911d826a7d to your computer and use it in GitHub Desktop.

Select an option

Save shriyanss/2cc7db449ae3ba12b08f6b911d826a7d to your computer and use it in GitHub Desktop.
Read GPS from Neo-6M GPS Module on a Raspberry Pi
import re
latitude = None
longitude = None
def parse_gprmc(sentence):
"""Parse GPRMC sentence to extract and convert GPS coordinates."""
parts = sentence.split(',')
if len(parts) < 7 or parts[2] != 'A': # Check for valid data (A = Active)
return None, None
# Parse latitude
lat_raw = parts[3]
lat_dir = parts[4]
lat_deg = int(lat_raw[:2])
lat_min = float(lat_raw[2:])
latitude = lat_deg + (lat_min / 60)
if lat_dir == 'S':
latitude = -latitude
# Parse longitude
lon_raw = parts[5]
lon_dir = parts[6]
lon_deg = int(lon_raw[:3])
lon_min = float(lon_raw[3:])
longitude = lon_deg + (lon_min / 60)
if lon_dir == 'W':
longitude = -longitude
return latitude, longitude
def read_gps():
"""Continuously read GPS data from /dev/ttyAMA0."""
with open('/dev/ttyAMA0', 'r') as gps:
while True:
line = gps.readline().strip()
if line.startswith('$GPRMC'):
lat, lon = parse_gprmc(line)
if lat is not None and lon is not None:
print(f"Latitude: {lat:.5f}, Longitude: {lon:.5f}")
latitude = f"{lat:.5f}"
longitude = f"{lat:.5f}"
if __name__ == "__main__":
read_gps()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment