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 函数一次读取多个字符
基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
