Python Serial:如何使用 read 或 readline 函数一次读取多个字符

2022-01-18 00:00:00 python readline pyserial serial-port

问题描述

我无法使用我的程序读取多个字符,我似乎无法弄清楚我的程序出了什么问题.

I'm having trouble to read more than one character using my program, I can't seem to figure out what went wrong with my program.

import serial

ser = serial.Serial(
    port='COM5',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
        timeout=0)

print("connected to: " + ser.portstr)
count=1

while True:
    for line in ser.read():

        print(str(count) + str(': ') + chr(line) )
        count = count+1

ser.close()

这是我得到的结果

connected to: COM5
1: 1
2: 2
3: 4
4: 3
5: 1

其实我早就料到了

connected to: COM5
1:12431
2:12431

类似于上面提到的东西,它可以同时读取多个字符,而不是一个一个.

something like the above mentioned which is able read multiple characters at the same time not one by one.


解决方案

我发现了几个问题.

第一:

ser.read() 一次只会返回 1 个字节.

ser.read() is only going to return 1 byte at a time.

如果您指定计数

ser.read(5)

它将读取 5 个字节(如果在 5 个字节到达之前发生超时,则更少.)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

如果您知道您的输入始终以 EOL 字符正确终止,更好的方法是使用

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

这将继续读取字符,直到收到 EOL.

That will continue to read characters until an EOL is received.

第二:

即使你让 ser.read() 或 ser.readline() 返回多个字节,由于您正在迭代返回值,因此您将仍然一次处理一个字节.

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

摆脱

for line in ser.read():

然后说:

line = ser.readline()

相关文章