Skip to content

Instantly share code, notes, and snippets.

@farhangnaderi
Created April 2, 2023 09:09
Show Gist options
  • Save farhangnaderi/f5ffa38b1540b3f59c436b6b5ff5c937 to your computer and use it in GitHub Desktop.
Save farhangnaderi/f5ffa38b1540b3f59c436b6b5ff5c937 to your computer and use it in GitHub Desktop.
import serial
import pynmea2
# Open the serial port
ser = serial.Serial('/dev/ttyUSB0', 115200)
# Read and print the output
while True:
try:
data = ser.readline().decode('ascii', errors='ignore').strip()
if data.startswith('$GNGGA'):
msg = pynmea2.parse(data)
print('Latitude: {0:.6f}, Longitude: {1:.6f}'.format(msg.latitude, msg.longitude))
elif data.startswith('$GNRMC'):
msg = pynmea2.parse(data)
speed = getattr(msg, 'spd_over_grnd', None)
course = getattr(msg, 'true_course', None)
if speed is not None and course is not None:
print('Speed: {0:.2f} knots, Course: {1:.2f} degrees'.format(speed, course))
elif data.startswith('$GNGLL'):
msg = pynmea2.parse(data)
print('Latitude: {0:.6f}, Longitude: {1:.6f}'.format(msg.latitude, msg.longitude))
else:
print(data)
except KeyboardInterrupt:
# Close the serial port on Ctrl-C
ser.close()
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment