Repository navigation
Expand file tree
/
Copy pathgpstest2.py
More file actions
82 lines (58 loc) · 1.99 KB
/
Copy pathgpstest2.py
File metadata and controls
82 lines (58 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
"""
Read GPS coordinates from a u-blox USB receiver and print them (no logging).
"""
import argparse
import serial
def nmea_to_decimal(value, direction):
if not value or not direction:
return None
try:
raw = float(value)
except ValueError:
return None
degrees = int(raw // 100)
minutes = raw - (degrees * 100)
decimal = degrees + (minutes / 60.0)
if direction in ("S", "W"):
decimal *= -1
return decimal
def parse_line(line):
if not line.startswith("$"):
return None
parts = line.strip().split(",")
# GGA sentence (has altitude)
if parts[0].endswith("GGA") and len(parts) > 9:
lat = nmea_to_decimal(parts[2], parts[3])
lon = nmea_to_decimal(parts[4], parts[5])
alt = parts[9]
if lat and lon:
return lat, lon, alt
# RMC sentence (no altitude, but good fallback)
if parts[0].endswith("RMC") and len(parts) > 6 and parts[2] == "A":
lat = nmea_to_decimal(parts[3], parts[4])
lon = nmea_to_decimal(parts[5], parts[6])
if lat and lon:
return lat, lon, None
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--port", required=True, help="Serial port (e.g. COM3 or /dev/ttyACM0)")
parser.add_argument("--baudrate", type=int, default=19200)
args = parser.parse_args()
ser = serial.Serial(args.port, args.baudrate, timeout=1)
print(f"Reading GPS from {args.port} (Ctrl+C to stop)\n")
try:
while True:
line = ser.readline().decode("ascii", errors="ignore").strip()
result = parse_line(line)
if result:
lat, lon, alt = result
if alt:
print(f"Lat: {lat:.6f}, Lon: {lon:.6f}, Alt: {alt} m")
else:
print(f"Lat: {lat:.6f}, Lon: {lon:.6f}")
except KeyboardInterrupt:
print("\nStopped.")
if __name__ == "__main__":
main()