问题描述
我有一个 Arduino 连接到我的计算机运行循环,每 100 毫秒通过串行端口向计算机发送一个值.
I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
我想制作一个 Python 脚本,每隔几秒钟从串口读取一次数据,所以我希望它只看到从 Arduino 发送的最后一件事.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
你如何在 Pyserial 中做到这一点?
How do you do this in Pyserial?
这是我试过但不起作用的代码.它按顺序读取行.
Here's the code I tried which does't work. It reads the lines sequentially.
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 中,直到您阅读它.
Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.
如果你想有一个状态显示来显示最新发送的东西 - 使用一个线程在你的问题中包含代码(减去睡眠),并保持最后一行作为来自 Arduino 的最新行读取.
If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your question (minus the sleep), and keep the last complete line read as the latest line from the Arduino.
更新: mtasic
的示例代码相当不错,但是如果 Arduino 在调用 inWaiting()
时发送了部分行,你会得到一条截断的线.相反,您想要做的是将最后的 complete 行放入 last_received
中,并将部分行保留在 buffer
中,以便它可以附加到下一次循环.像这样:
Update: mtasic
's example code is quite good, but if the Arduino has sent a partial line when inWaiting()
is called, you'll get a truncated line. Instead, what you want to do is to put the last complete line into last_received
, and keep the partial line in buffer
so that it can be appended to the next time round the loop. Something like this:
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()):
Regarding use of readline()
: Here's what the Pyserial documentation has to say (slightly edited for clarity and with a mention to readlines()):
使用readline"时要小心.做打开时指定超时串口,否则会阻塞如果没有换行符,则永远已收到.还要注意readlines()"仅适用于超时.它取决于超时和将其解释为 EOF(文件结尾).
这对我来说似乎很合理!
which seems quite reasonable to me!
这篇关于pyserial - 如何读取从串行设备发送的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!