简体   繁体   English

在 Python 中 5 秒后停止等待串行响应

[英]Stop waiting for serial response after 5 seconds in Python

I am trying to get a response from a serial port, but sometimes there will be none .我想从一个串行端口的响应,但有时会出现没有 This makes my script wait forever , thus I have to kill it.这使我的脚本永远等待,因此我必须杀死它。

Is there a simple way to make my code wait for example 5 seconds and if there was no response continue with the script?有没有一种简单的方法可以让我的代码等待 5 秒,如果没有响应,请继续执行脚本?

My code looks like this:我的代码如下所示:

import serial
ser = serial.Serial('COM3', 9600)

test = '2ho0'

ser.write(str.encode(test))
data = ser.readline()
print(data)

I have tried this solution, but it does not stop after 5 prints of Hello world .我已经尝试过这个解决方案,但在打印 5 次Hello world后它不会停止。 Instead, it continues writing Hello World , until I get a runtime error .相反,它会继续编写Hello World ,直到出现runtime error

Over here and here I tried severeal answers with no success either.这里这里,我尝试了严厉的回答,但也没有成功。

EDIT: I am wondering if it is possible to have something like:编辑:我想知道是否有可能有类似的东西:

ser.serialReplyAvailable()

This would do the job for me as well.这也适合我。

Thanks for any advice.感谢您的任何建议。

You can specify a read timeout which will make the ser.readline() either return immediately if the requested data is available, or return whatever was read until the timeout expired.您可以指定读取超时,这将使ser.readline()要么在请求的数据可用时立即返回,要么返回在超时到期之前读取的任何内容。 Check the pySerial docs there is more on this there.检查 pySerial 文档,那里有更多相关内容。

ser = serial.Serial('COM3', 9600, timeout=5)

You could try wrapping the readline into a while Statement and have a timer tick inside if the reading was not successful.如果读取不成功,您可以尝试将 readline 包装到 while 语句中,并在里面有一个计时器滴答声。 If it is, break out of it.如果是,就摆脱它。

from time import sleep
tries = 0
while tries < 4:
    data = ser.readline()
    if data != None: #Or "", whatever the return data
        break
    sleep(5); tries += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM