使用 PySerial 是否可以等待数据? [英] Using PySerial is it possible to wait for data?

查看:56
本文介绍了使用 PySerial 是否可以等待数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a Python program which is reading data from a serial port via the PySerial module. The two conditions I need to keep in mind are: I don't know how much data will arrive, and I don't know when to expect data.

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

Based on this I have came up with the follow code snippets:

#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 个字符的数据存储,然后通过设置一个标志来提醒主循环.如果没有数据存在,我们将返回休眠并等待.

So this code will loop forever getting data off the serial port. We'll get up to 500 characters store the data, then alert the main loop by setting a flag. If no data is present we'll just go back to sleep and wait.

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

The code is working, but I don't like the 5s timeout. I need it because I don't know how much data to expect, but I don't like that it's waking up every 5 seconds even when no data is present.

在执行读取之前,有没有办法检查数据何时可用?我在想类似于 Linux 中的 select 命令.

Is there any way to check when data becomes available before doing the read? I'm thinking something like the select command in Linux.

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

Note: I found the inWaiting() method, but really that seems it just change my "sleep" to a poll, so that's not what I want here. I just want to sleep until data comes in, then go get it.

推荐答案

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

Ok, I actually got something together that I like for this. Using a combination of read() with no timeout and the inWaiting() method:

#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 中不作为单一方法存在

This seems to give the results I wanted, I guess this type of functionality doesn't exist as a single method in Python

这篇关于使用 PySerial 是否可以等待数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆