jdz/gps_new.py

53 lines
1.7 KiB
Python
Raw Normal View History

2024-07-23 03:02:56 +00:00
import serial
import csv
import time
from datetime import datetime
# Configure the serial port
ser = serial.Serial('/dev/ttyS0', baudrate=9600, timeout=1)
# Open the CSV file for writing
csv_filename = 'gps_data.csv'
csv_file = open(csv_filename, 'w', newline='')
csv_writer = csv.writer(csv_file)
# Write the header row
csv_writer.writerow(['Timestamp', 'Latitude', 'Longitude'])
try:
while True:
# Read a line from the GPS device
line = ser.readline().decode('ascii', errors='replace').strip()
# Check if it's a GPRMC sentence (which contains coordinate data)
if line.startswith('$GPRMC'):
parts = line.split(',')
if len(parts) >= 7 and parts[2] == 'A': # 'A' means data is valid
# Extract latitude and longitude
lat = float(parts[3][:2]) + float(parts[3][2:]) / 60
if parts[4] == 'S':
lat = -lat
lon = float(parts[5][:3]) + float(parts[5][3:]) / 60
if parts[6] == 'W':
lon = -lon
# Get current timestamp
timestamp = datetime.now().isoformat()
# Write to CSV
csv_writer.writerow([timestamp, lat, lon])
csv_file.flush() # Ensure data is written to file
print(f"Recorded: {timestamp}, Lat: {lat}, Lon: {lon}")
time.sleep(1) # Wait for 1 second before reading next line
except KeyboardInterrupt:
print("Script terminated by user")
finally:
# Close the serial port and CSV file
ser.close()
csv_file.close()
print(f"Data saved to {csv_filename}")