无Inpu时循环超时

2024-03-29 01:50:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,完全符合我的需要,除非有一件事,超时。你知道吗

基本上,此代码将每隔0,5s记录一个条目,持续3秒,然后打印“完成”,然后重新启动。我要记录的声音是恒定的,大约3,1秒,所以这是完美的。每次声音出现时,它都会打印“完成”

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)
pin = 7 #Defining pin 7 as Input pin
GPIO.setup(pin, GPIO.IN)

list = ["Start"]

while l:
    if GPIO.input(pin) == GPIO.LOW: #This is the input
        if len(list) <= 6:
            list.insert(0, "Entry") #Insert into list at first position
            sleep(0.5) #If there is a constant sound, this makes sure a new item is interted only every 0,5s.
            print ("Not Done")
            print (len(list))

        elif len(list) > 6:
            list = ["Start"]
            print ("Done")

所以现在,如果代码检测到声音并记录下来,我希望代码重新启动,但是在1到2秒钟内什么都没有发生。你知道吗

因此,如果列表长度达到3或4个单位,但在一两秒钟内什么也没有发生,那么它必须回到1个单位长。你知道吗

我希望这有道理。我希望你们都能帮助我。你知道吗

非常感谢!你知道吗


Tags: 代码import声音inputgpiolenifis
1条回答
网友
1楼 · 发布于 2024-03-29 01:50:36

你想要一个长音成为一个信号。你希望没有声音就没有信号,短声音就没有信号。你知道吗

sound_present_for_samples = 0
logging_threshold = 6  # 6 half seconds
while True:
    if GPIO.input(pin) == GPIO.LOW:
        sound_present_for_samples += 1
        if sound_present_for_samples == threshold:
            print("Done")
        elif sound_present_for_samples < threshold:
            print("Not done")
        sleep(0.5)
    else:
        sound_present_for_samples = 0

你真的不需要这里的清单。sound_present_for_samples中的数字是普通列表中的“条目”数。你可以随时建造它。["Entry"]*sound_present_for_samples前面添加了[“Start”]。你知道吗

如果需要列表中的实际数据而不是字符串,还可以用列表替换sound_present_for_samples,用.append替换every+=1,用=[]替换=0,用len(spfs)替换条件。你知道吗

相关问题 更多 >