gpt4 book ai didi

python - pyserial - 如何读取从串行设备发送的最后一行

转载 作者:IT老高 更新时间:2023-10-28 20:49:22 25 4
gpt4 key购买 nike

我有一个 Arduino 连接到我的计算机并运行一个循环,每 100 毫秒通过串行端口将一个值发送回计算机。

我想制作一个 Python 脚本,每隔几秒钟从串口读取一次,所以我希望它只看到从 Arduino 发送的最后一件事。

你如何在 Pyserial 中做到这一点?

这是我尝试过的代码,但它不起作用。它按顺序读取行。

import serial
import time

ser = serial.Serial('com4',9600,timeout=1)
while 1:
time.sleep(10)
print ser.readline() #How do I get the most recent line sent from the device?

最佳答案

也许我误解了您的问题,但由于它是串行线路,您必须按顺序读取从 Arduino 发送的所有内容 - 在您阅读之前,它将在 Arduino 中缓冲。

如果您想要显示最新发送的内容的状态显示 - 使用包含问题中代码的线程(减去 sleep ),并将最后一个完整行读取为 Arduino 的最新行。

更新: mtasic 的示例代码相当不错,但是如果调用 inWaiting() 时 Arduino 发送了部分行,你会得到一条截断的线。相反,您要做的是将最后 complete 行放入 last_received,并将部分行保留在 buffer 中,以便它可以附加到下一次循环。像这样的:

def receiving(ser):
global last_received

buffer_string = ''
while True:
buffer_string = buffer_string + ser.read(ser.inWaiting())
if '\n' in buffer_string:
lines = buffer_string.split('\n') # Guaranteed to have at least 2 entries
last_received = lines[-2]
#If the Arduino sends lots of empty lines, you'll lose the
#last filled line, so you could make the above statement conditional
#like so: if lines[-2]: last_received = lines[-2]
buffer_string = lines[-1]

关于 readline() 的使用:以下是 Pyserial 文档的内容(为清楚起见,稍作编辑并提及 readlines()):

Be careful when using "readline". Do specify a timeout when opening the serial port, otherwise it could block forever if no newline character is received. Also note that "readlines()" only works with a timeout. It depends on having a timeout and interprets that as EOF (end of file).

这对我来说似乎很合理!

关于python - pyserial - 如何读取从串行设备发送的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1093598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com