2014-02-12 105 views
0

我想本GPS位置讀數,當我運行在覆盆子PI下面的代碼,程序打印10-12輸出,然後將其顯示錯誤如下解析:
回溯(最近呼叫最後):
文件 「simplegpsparsing.py」,第24行,在
get_present_gps()
文件 「simplegpsparsing.py」,第16行,在get_present_gps
LAT,_,LON = line.split( '' )[2:5]
ValueError:需要多個值才能解包
i wa nt當前的GPS值(緩衝區應該用即時GPS更新),以便可以知道當前的GPS值。 我的代碼去如下:
NMEA數據使用python 2.7

import os 
import serial 
def get_present_gps: 
    ser= serial.Serial('/dev/ttyAMA0',9600) 
    ser.open() 
    while True : 
     f=open('/home/pi/Desktop/gps1','w') 
     data=ser.read(ser.inWaiting()) # read no.of bytes in waiting 
     f.write(data) #write data into file 
     f.flush() # flush(method) from buffer into os buffer 
     os.fsync(f.fileno()) #ensure to write from os buffer(internal buffers)into disk 
     f = open('/home/pi/Desktop/gps1','r') # fetch the required file 
     for line in f.read().split('\n') : 
      if line.startswith('$GPGGA') : 
       lat, _, lon = line.strip().split(',')[2:5] 
       try : 
        lat = float(lat) 
        lon = float(lon) 
        print lat 
        print lon 
       except : 
        pass 

     # something wrong happens with your data, print some error messages 
get_present_gps()    

如果串行端口是開放的,但不關閉,將它造成任何問題?上述代碼是否符合我的要求即獲得瞬時值?

+0

你應該等到你有一個完整的行......即不要處理一個不以'\ n'結尾的行。但是,不應該擔心你打開串口。 – Floris

+0

爲什麼要將數據寫入文件?你不能直接解析'data'變量嗎?這可能會更容易... – Floris

+0

@弗洛伊斯你能指導我如何做到這一點,是的嘗試尋找它,不幸的是我得到了一些其他結果.. –

回答

0

這是一個想法:將數據字符串解析爲換行符終止的塊;在緩衝區中留下「未完成」的字符串,直到下一次循環。未經測試,這看起來是這樣的:

keepThis = '' 
while True : 
    data=keepThis + ser.read(ser.inWaiting()) # read no.of bytes in waiting 
    m = data.split("\n") # get the individual lines from input 

    if len(m[-1]==0): # true if only complete lines present (nothing after last newline) 
     processThis = m 
     keepThis = '' 
    else: 
     processThis = m[0:-1] # skip incomplete line 
     keepThis = m[-1]  # fragment 

    # process the complete lines: 
    for line in processThis: 
     if line.startswith('$GPGGA') : 
      try : 
      lat, _, lon = line.strip().split(',')[2:5] # move inside `try` just in case... 
      lat = float(lat) 
      lon = float(lon) 
      print lat 
      print lon 
      except : 
      pass 
+0

我得到這個錯誤:回溯(最近通話最後一個): 文件 「stack1.py」,第29行,在 get_present_gps() 文件 「stack1.py」,13號線,在get_present_gps 如果len(M [ -1] == 0): TypeError:'bool'類型的對象沒有len()這裏有錯誤在括號中的錯誤位置? –

+0

我改變了如果len(m [-1] == 0):如果len(m [-1] 0 == 0:我得到一些不在我們指定範圍內的隨機值,我想嘗試其他方法將數據保存到文件並執行相同的操作,它會使它有所不同嗎?而我在這裏沒有得到的是爲什麼打印出的值超出範圍(2:5) –

+0

對不起,這是一個錯字 - 應該是' if(len(m [-1])== 0):'。需要更仔細地瞭解你提出的其他問題/評論 – Floris