2011-03-21 96 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