python从串口GPS读取

时间:2015-06-01 18:55:36

标签: python serial-port

我做了一个python程序,从串口读取gps数据。当插入USB时,GPS冰球连续流式传输NMEA数据句子。我的程序打开端口,然后尝试读取数据,解析数据,然后将其写入文本文件以及从Arduino中提取的其他数据。

我遇到的问题是偶尔在我第一次运行程序时无法读取数据。我把一些Try / Exception捕获并发现它无法以某种方式从GPS串口读取数据 如果我多次点击Cntrl-C,这似乎将它从遇到的问题中解脱出来,然后它开始正常工作。我倾向于认为它是一个时间问题,当GPS在流媒体和程序试图读取串行缓冲区时。

显然我在代码中做错了。我尽可能地把它拼凑在一起,并且为了我的目的它可以正常工作,但可以做一些帮助,使它更坚固,所以其他可能使用它的人不会被它的片状行为所困惑。 / p>

下面是这里(由于Notepad ++中的复制粘贴,一些缩进是错误的)。任何帮助都会很棒。

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 个答案:

答案 0 :(得分:0)

您可以通过打印获得有关例外的其他信息。

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

您也可以尝试将arduino.flushInput()放在循环之外。根据时间安排,您可能会丢失一些数据。