串行端口read()在数据可用时不返回(python/cygwin)

2024-10-02 10:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我用电脑上的Cygwin访问pySerial的串行端口。 我的组件是一个USB组件,连接到一个响应查询的设备。 我们有36个组件,我使用的是COM36(/dev/ttyS35)。在

考虑到我们的库,我需要继续使用Python2.7。 我在端口上做一个读(),它总是等待直到读取数据i的长度,而不是返回数据,当数据可用时,就像它将在C++中一样。在

使用'timeout'参数不是一个选项,因为它会迫使它每次都等待超时。太短,它会丢失数据和旋转占用处理器时间,而太长则会减慢程序速度。我知道在C++应用程序中,库等待至少一个字节被读取,并继续读取更多,直到在返回之前读取的字节之间有一个“重要”的暂停。我想要python中的行为。在

当我看到串行构造函数的“interCharTimeout”时,我以为我找到了我的答案,但那没用。它仍然挂起,直到100个字节都被读取。 然后我查看PySerial代码,发现它没有在对象中设置正确的var(可能是错误的),所以我直接调用了'setInterChartTimeout'方法。但结果还是一样。在

下面是我的简单代码示例。在

#!/bin/env python

import serial
from lib.Hex import *

# COM35, a USB serial port
s = serial.Serial(port="/dev/ttyS34", baudrate=19200, interCharTimeout=0.01)
s.close()
s.open()
s.setInterCharTimeout( 0.01 )
s.setTimeout( 2 )

# Send message the causes the device to generate a reply
data = fromHex( "AABB01072851EE" )
s.write( data )

data = s.read(100) # Note: this does return data if 'timeout' was used
print "Got: ", toHex(data)

我读了posixserial.py代码和我看到序列总是循环直到所有字节都被读取。然后我看到PosixPollSerial重写了read()。我试着用这个。在

^{pr2}$

但是我得到了一个错误:

Traceback (most recent call last):
File "./go2.py", line 18, in <module>
  data = s.read(100)
File "/usr/lib/python2.7/site-packages/pyserial-2.7-py2.7.egg/serial/serialposix.py", line 672, in read
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

线路672英寸serialposix.py这是:

672                 for fd, event in poll.poll(self._timeout*1000):

Tags: 数据端口代码inpydevreaddata
1条回答
网友
1楼 · 发布于 2024-10-02 10:27:55

检查以下各项:

pySerial 3.0 documentation: serial.Serial.in_waiting
in_waiting
Getter: Get the number of bytes in the input buffer
Type: int
Return the number of bytes in the receive buffer.
Changed in version 3.0: changed to property from inWaiting()

例如,read all waiting或至少读1serial.in_waiting or 1。在

B_SIZE = 10

def RxEvent(b):
    print('RxEvent(%s) %d' % (b, len(b)))

def Thread_serial_read(serial, alive, rxEvent):
    serial.timeout = 0.5  # make sure that the alive event can be checked from time to time
    n = 0
    b_tmp = []
    while alive.isSet():
        time.sleep(0.25)
        b = serial.read(serial.in_waiting or 1)
        if b:
            b_tmp.extend(b)
            n += len(b)
            if n >= B_SIZE:
                rxEvent( b_tmp[:B_SIZE] )
                b_tmp = b_tmp[B_SIZE:]
                n = len(b_tmp)

if __name__ == '__main__':
    alive = threading.Event()
    Thread_serial_read(Serial(), alive, RxEvent)

测试Python:3.4.2和2.7.9

相关问题 更多 >

    热门问题