From 4cdd89a0fc92ff9151532a7eb1930fd3572b8ac2 Mon Sep 17 00:00:00 2001 From: Adolfo Delorenzo Date: Fri, 12 Jul 2024 01:13:29 +0000 Subject: [PATCH] Add GPS2.py --- GPS2.py | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 GPS2.py diff --git a/GPS2.py b/GPS2.py new file mode 100644 index 0000000..46052c7 --- /dev/null +++ b/GPS2.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import sqlite3 +import serial +import time, os + +# SQLite Database settings +db_file = "gps_coordinates.db" +conn = sqlite3.connect(db_file) +cursor = conn.cursor() + +ser = serial.Serial('/dev/ttyS0',115200) +ser.flushInput() + +def send_at(command,back,timeout): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01 ) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + print(rec_buff.decode()) + return 1 + else: + print('GPS is not ready') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Iniciando GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + if 1 == answer: + answer = 0 + if ',,,,,,' not in rec_buff: + # Extract GPS information from rec_buff and store it in the database + gps_info = extract_gps_info(rec_buff) # Implement this function based on the format of rec_buff + store_gps_coordinates(gps_info) + return True + else: + print('GPS is not ready') + time.sleep(1) + else: + print('error %d' % answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + +def extract_gps_info(rec_buff): + # Implement this function based on the format of rec_buff + # Example: gps_info = rec_buff.split(',')[2] + return gps_info + +def store_gps_coordinates(gps_info): + cursor.execute("INSERT INTO coordinates (latitude, longitude) VALUES (?, ?)", gps_info) + conn.commit() + +# Main program +if __name__ == '__main__': + # Create the SQLite table if it doesn't exist + cursor.execute('''CREATE TABLE IF NOT EXISTS coordinates (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude REAL, longitude REAL)''') + while True: + get_gps_position() \ No newline at end of file