gpt4 book ai didi

python - 使用 PySerial 是否可以等待数据?

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

我有一个 Python 程序,它通过 PySerial 模块从串行端口读取数据。我需要记住的两个条件是:我不知道有多少数据会到达,我不知道什么时候会收到数据。

基于此,我想出了以下代码片段:

#Code from main loop, spawning thread and waiting for data
s = serial.Serial(5, timeout=5) # Open COM5, 5 second timeout
s.baudrate = 19200

#Code from thread reading serial data
while 1:
tdata = s.read(500) # Read 500 characters or 5 seconds

if(tdata.__len__() > 0): #If we got data
if(self.flag_got_data is 0): #If it's the first data we recieved, store it
self.data = tdata
else: #if it's not the first, append the data
self.data += tdata
self.flag_got_data = 1

因此,此代码将永远循环从串行端口获取数据。我们将获得多达 500 个字符来存储数据,然后通过设置一个标志来提醒主循环。如果没有数据,我们就回去 sleep 等待。

代码可以运行,但我不喜欢 5s 超时。我需要它,因为我不知道需要多少数据,但我不喜欢它每 5 秒醒来一次,即使没有数据存在。

在执行 read 之前,有什么方法可以检查数据何时可用?我正在考虑类似于 Linux 中的 select 命令。

注意:我找到了 inWaiting() 方法,但实际上这似乎只是将我的“ sleep ”更改为投票,所以这不是我想要的。我只是想 sleep ,直到数据进来,然后去拿它。

最佳答案

好的,我实际上为此收集了一些我喜欢的东西。结合使用没有超时的 read()inWaiting() 方法:

#Modified code from main loop: 
s = serial.Serial(5)

#Modified code from thread reading the serial port
while 1:
tdata = s.read() # Wait forever for anything
time.sleep(1) # Sleep (or inWaiting() doesn't give the correct value)
data_left = s.inWaiting() # Get the number of characters ready to be read
tdata += s.read(data_left) # Do the read and combine it with the first character

... #Rest of the code

这似乎给出了我想要的结果,我猜这种类型的功能在 Python 中不作为单一方法存在

关于python - 使用 PySerial 是否可以等待数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13017840/

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