Python Serial: How to use the read or readline function to read more than 1 character at a time(Python Serial:如何使用 read 或 readline 函数一次读取多个字符)
问题描述
我无法使用我的程序读取多个字符,我似乎无法弄清楚我的程序出了什么问题.
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()
这篇关于Python Serial:如何使用 read 或 readline 函数一次读取多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python Serial:如何使用 read 或 readline 函数一次读取多个字符


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01