4

pySerial用来读取 TTL 字节流。读取两个字节:

CheckSumByte = [ b for b in ser.read(2)]
print( CheckSumByte)
print( type(CheckSumByte))
print( str(len(CheckSumByte)))
print( CheckSumByte[0])

输出:

[202, 87]
<class 'list'>
2
IndexError: list index out of range

我无法CheckSumByte按索引(0 或 1)访问任何元素。怎么了?

这是我的代码:

while(ReadBufferCount < 1000):
    time.sleep(0.00002)
    InputBuffer = ser.inWaiting()
    if (InputBuffer > 0):
        FirstByte = ser.read(1)
        if ord(FirstByte) == 0xFA:
            while ser.inWaiting() < 21: pass
        IndexByte = ser.read(1)
        SpeedByte = [ b for b in ser.read(2)]
        DataByte0 = [ b for b in ser.read(4)]
        DataByte1 = [ b for b in ser.read(4)]
        DataByte2 = [ b for b in ser.read(4)]
        DataByte3 = [ b for b in ser.read(4)]
        CheckSumByte = [ b for b in ser.read(2)]
        print( CheckSumByte[0]) #Out of Range??`
Traceback (most recent call last):

  File "<ipython-input-6-5233b0a578b1>", line 1, in <module>
    runfile('C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py', wdir='C:/Users/Blair/Documents/Python/Neato XV-11 Lidar')

  File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
    execfile(filename, namespace)

  File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

  File "C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py", line 88, in <module>
    print( CheckSumByte[0]) #Out of Range??

IndexError: list index out of range

肯尼:谢谢。两个字节更简单:

    CheckSumByte.append(ser.read(1))
    CheckSumByte.append(ser.read(1))

工作正常,但尴尬。这些项目是类型字节。如何使用列表推导将项目添加到列表中?我想避免 append 功能,因为它很慢。

我注意到当 CheckSumByte 的项目是整数时它不起作用。Python 3 列表理解是否需要特殊格式才能将字节添加为字节(不转换为整数)?

4

1 回答 1

2

根据您最近的评论,您构建ser为:

ser = serial.Serial(
    port=PortName, baudrate=115200, parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, 
    timeout=0)

根据文档,这意味着它ser非阻塞的(尽管您断言它是阻塞的!)。

由于它处于非阻塞模式,因此绝对没有理由期望ser.read(n)准确返回n字节。相反,如果您想读取n字节,您应该:

  • 在构造函数中构造ser为阻塞(使用timeout=None);或者
  • 在监视实际读取的字节数时循环(就像在读取网络套接字时一样)

例如,后者意味着如果您希望读取n字节,则需要执行以下操作:

def read_exactly(ser, n):
    bytes = b""

    while len(bytes) < n:
        bytes += ser.read(n - len(bytes))

    return bytes

在您的特定情况下,您似乎正在监视输入缓冲区以确保有足够的数据用于以下读取。但这种监控只是在某些时候发生,而不是所有时间。因此,FirstByte != 0xFA除非您采用上面给出的方法之一,否则当您可能耗尽读取缓冲区时。

于 2017-03-28T03:24:34.883 回答