2011-03-21 95 views
0

我有一個python程序試圖從串口讀取14個字節,這個串口在 的到達非常緩慢。我想要捕獲一個 bytearray [14]中的所有字節。我明白在python 3.0中有新的字節數組功能,但是 我只運行python 2.6.6。升級可能會產生意想不到的後果,所以我必須 堅持2.6.6。從python中的串口讀取數據時的問題

數據只能間歇地流過串口。我可能每隔2分鐘左右在端口 上收到一條消息。這些數據流動非常緩慢。我看到的問題是 ,我的代碼一次不能可靠地讀取一個字節的數據。我想將這個 數據精確地組成14個字節,然後處理數據並以新的字節開始新的數據。

我在這裏採取了錯誤的做法?建議嗎?

ser = serial.Serial('/dev/ttyUSB1', 1200, timeout=0) 
    ser.open() 
    print "connected to: " + ser.portstr 
    count=0 
    while True: 
     line =ser.readline(size=14) # should block, not take anything less than 14 bytes 
     if line: 
      # Here I want to process 14 bytes worth of data and have 
      # the data be consistent. 
      print "line(" + str(count) + ")=" + line 
      count=count+1 
    ser.close() 

這裏就是我期待:線(1)=在回車

0〜888.ABC /結束----------開始輸出--- ---

line(0)=0 
line(1)=~ ??1. ABC � # here get some multiple bytes and stuff gets out of synch 

�ine(2)= 
line(3)=0 
line(4)=~ 
line(5)= 
line(6)=8 
line(7)=8 
line(8)=8 
line(9)=. 
line(10)= 
line(11)=A 
line(12)=B 
line(13)=C 
line(14)= 
line(15)=� 
line(16)= 

#... 
line(48)= 
line(49)=� 
line(50)=0 
line(51)=~ 
line(52)= 
line(53)=8 
line(54)=8 
line(55)=8 
line(56)=. 
line(57)= 
line(58)=A 
line(59)=B 
line(60)=C 
line(61)= 
line(62)=� 
line(63)= 

line(64)= 

----------端輸出------

回答

4

爲PySerial API文檔說readline()讀取直到\ n或直到達到大小。但是,read()函數表示它會阻塞,直到達到大小。這兩個函數都表示如果設置了超時時間,它們會提前返回。

Possible values for the parameter timeout: 

timeout = None: wait forever 
timeout = 0: non-blocking mode (return immediately on read) 
timeout = x: set timeout to x seconds (float allowed) 

也許嘗試的timeout=None代替timeout=0

2

試試這個:

ser = Serial('/dev/ttyUSB1', 1200, timeout=0) 
print "connected to: " + ser.portstr 
count=0 
while True: 
    for line in ser.readlines() 
      print "line(" + str(count) + ")=" + line 
      count=count+1 

ser.close() 

您可能也有興趣在line.strip()功能,如果你還沒有使用過。此外,強調的在ser.readlines(),不同於.readline()

-1

更改波特率。

ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=0) 

到兼容的波特率。

爲了得到14字節的數據:

data = ser.read(size=14) 
+0

什麼是你的建議不同波特率的理由? OP的例子顯示接收預期的數據(只是不是全部在一個讀取),這表明波特率是正確的。 – NickS 2016-06-16 17:55:39