0

I made a python program that reads the gps data from the serial port. The GPS puck streams the NMEA data sentences continuously when plugged into the USB. My program opens the port and then attempts to read the data, parse it, and then write it to a text file along with other data pulled from an Arduino.

The problem I am having is that once in a while it fails to read the data when I first run the program. I put some Try/Exception catches in and found its a failure to read the data from the GPS serial port in some way.
If I hit Cntrl-C a couple of times this seems to knock it out of the problem its encountering and then it starts to work fine. I'm inclined to think its a timing issue of when the GPS in streaming and when the program is trying to read the serial buffer.

Obviously I've done something incorrectly in my code. I sorta just slapped it together as best I could and for my purposes it works fine but could do with a little bit of help in making it more rock solid so other people that might use it won't be baffled by its flaky behaviour.

Here it is below (some of the indents are wrong because of the copy paste from Notepad++). Any help would be great.

import serial
import pynmea2
import time
#####Global Variables######################################
#be sure to declare the variable as 'global var' in the functions

ID = 0
arduino = 0
ser2 = 0
fh = ""
rssi_dB = 0
gps = "NaN"

#    User configurable

gps_com_port = 19   # com 19 Shop7 at Hm 8
arduino_com_port = 18  # com 18 Shop7 at Hm 6

#    MCS2000 specific conversion rates
#    DON'T CHANGE!!!
slope1 = 0.0170
slope2 = 0.008
slope3 = 0.020
slope4 = 0.000
cutoff1 = 700
cutoff2 = 430
cutoff3 = 380
cutoff4 = 0
cutoff5 = 0
y_int1 = 3.399
y_int2 = 2.692
y_int3 = 3.949


#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
COMNUM1 = arduino_com_port #set you COM port # here
COMNUM2 = gps_com_port
global arduino #must be declared in each fxn used
global ser2
arduino = serial.Serial(
                    port = COMNUM1 -1,
                    baudrate = 9600,
                    timeout = 1
                    )
ser2 = serial.Serial(
                    port = COMNUM2 -1,
                    baudrate = 4800,
                    timeout = 1
                    )

if arduino.isOpen():
    print 'Open: ' + arduino.portstr
if ser2.isOpen():
    print 'Open: ' + ser2.portstr

def init_file():
filename = raw_input('Enter save file[name.txt]:')
global fh
fh = open(filename,"w")

def rssi_convert(rssi):
#print ("rssi_convert\n")    
if rssi<=cutoff1 and rssi>=cutoff2:
    rssi_dB=((rssi*0.004888)-y_int1)/slope1
if rssi<=cutoff2 and rssi>=cutoff3:
    rssi_dB=((rssi*0.004888)-y_int2)/slope2
if rssi<=cutoff3 and rssi>=cutoff4:
    rssi_dB=((rssi*0.004888)-y_int3)/slope3
#if rssi<=cutoff4 and rssi>=cutoff5:
 #   rssi_dB=((rssi*0.004888)-2.047)/slope4

return float(rssi_dB)


#####SETUP################################################
#this is a good spot to run your initializations 
init_file()
init_serial()
time.sleep(2)
data_log = "TOD,Lat,Long,Alt,Qual,Ref_ID,Num_Sat,Hor_Dil,RSSI\n"
fh.writelines(data_log)  #write header to file 
rssi = arduino.readline()    
while str(rssi) == "A":
arduino.write("q")
rssi = arduino.readline()

#####MAIN LOOP############################################
while 1:

arduino.flushInput()
try:
    gps = ser2.readline()
except:
    print("Read GPS FAILED\n")

try:    
    gps_msg = pynmea2.parse(gps)
except:
    print("Failed to parse GPS\n")

try:    
    if gps_msg.sentence_type == 'GGA':
        arduino.write("q")
        time.sleep(.2)
        rssi = arduino.readline()

        try:
            rssi_dB = rssi_convert(float(rssi.strip('\0')))
        except:
            print("RSSI Conversion FAILED\n")
        try:
            data_log = str(gps_msg.timestamp) + "," + str(gps_msg.latitude) + "," + str(gps_msg.longitude) + "," + str(gps_msg.altitude) + "," + str(gps_msg.gps_qual) + "," + str(gps_msg.ref_station_id) + "," + str(gps_msg.num_sats) + "," + str(gps_msg.horizontal_dil) + ","  + str(rssi_dB) + "\n"
            print str(ID) + data_log
            fh.writelines(data_log)  #write data to file
            ID = int(ID) + 1
        except:
            pass#ID=ID+1
except:
    print("GPS Sentence Loop Failed")

1 Answer 1

0

You can get additional info about the exception by printing it.

try:
    gps = ser2.readline()
except Exception as e:
    print('Read GPS failed: {0}'.format(e))

You might also try to put the arduino.flushInput() outside of the loop. Depending on the timing, you might be losing some of your data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.