python - Python X 秒后超时

标签 python serial-port timeout

我正在用 python 编写一个程序,其工作原理如下:

  1. 通过串口获取输入字符串,当按回车键时(回车 返回)
  2. 检查 $ 符号是否作为输入字符串的第一个字符出现,然后继续

Problem

如果我没有得到回车CR并且同时或在特定时间间隔后得到另一个字符串,这可能会造成麻烦。 为了避免这个问题,我想添加超时 session ,如果未收到回车符,则在特定时间间隔后使前一个缓冲区Null

请查看下面的代码并指导我如何在其中添加超时选项?

CODE

import serial

x = [0,0,0]
ser = serial.Serial('/dev/ttyAMA0', 9600)
buffer = ''
while True:
    buffer += ser.read(ser.inWaiting())
    if '\n' in buffer:
        if buffer[0] == '$':
            x1 = buffer.rstrip()
            x2= x1.split(",")
            print((x2[0]),(x2[1]),(x2[2]))
        buffer = ""

最佳答案

我认为你只需要在程序末尾添加这一行。 每次输入正确的字符串时,此行都会增加 60 秒

clear_buffer = time.time() + 60

查看下面的代码

import serial
import time

x = [0,0,0]
ser = serial.Serial('/dev/ttyAMA0', 9600)
buffer = ''
clear_buffer = time.time() + 60
while True:
    if time.time() >= clear_buffer:
        buffer = ''
        clear_buffer = time.time() + 60
    buffer += ser.read(ser.inWaiting())
    if '\n' in buffer:
        if buffer[0] == '$':
            x1 = buffer.rstrip()
            x2= x1.split(",")
            print((x2[0]),(x2[1]),(x2[2]))
        buffer = ""
        clear_buffer = time.time() + 60

关于python - Python X 秒后超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827608/

相关文章:

python - 将数据框行转换为 Python 集

Python - 处理 Unicode(俄语)Txt 文件

python - 获取多索引 pandas 系列的某个级别内序列的第一个和最后一个元素

serial-port - 通过arduino xbeeshield串行通信

linux - Socat 伪终端 : Can you make use of data lines (DTR, RTS 等)?

python - 在 Python 中打开文件时使用超时来防止死锁?

python - 调整散点图中的点大小

linux - 在 Linux 中锁定串行端口和其他设备的最佳做法是什么?

python - 使用 ftplib 在 Python 中设置 FTP 连接超时

python - 如何减少Python3请求中连接超时的等待?