树莓派Python实现按钮输入时间限制及嵌套循环超时退出
解决自主RC车Python代码中按钮输入的时间限制问题
我完全明白你的需求——给用户15秒的时间窗口来点击按钮,要么完成最多3次点击,要么超时就自动跳出内层循环。咱们来修改你的代码,加入时间跟踪的逻辑:
核心思路
咱们需要在内层循环开始时记录起始时间,之后每次循环都检查当前时间与起始时间的差值,一旦超过设定的15秒超时阈值,就触发跳出循环的条件。同时保留原有的“点击满3次就跳出”的逻辑。
修改后的完整代码
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) button1 = 26 GPIO.setup(button1, GPIO.IN, pull_up_down=GPIO.PUD_UP) # 定义超时时间(秒) CLICK_TIMEOUT = 15 print("Where do you want to go? Press once to go to the right, twice to go left or three times to go straight. Wait one second between clicks and you have 15 seconds to finish the process.") try: while True: clickCounter = 0 # 记录内层循环的起始时间 start_time = time.time() while True: # 检查是否超时 elapsed_time = time.time() - start_time if elapsed_time > CLICK_TIMEOUT: print(f"Time's up! You took longer than {CLICK_TIMEOUT} seconds.") break # 检查按钮是否被按下 if GPIO.input(button1) == 0: clickCounter += 1 print(f"Amount of clicks: {clickCounter}") # 防抖:避免按住按钮连续计数 time.sleep(1) # 点击满3次也跳出循环 if clickCounter == 3: break # 根据点击次数执行对应动作 if clickCounter == 0: print("Press the button 1-3 times within the time limit.") elif clickCounter == 1: print("We're going to the right.") break elif clickCounter == 2: print("We're going to the left.") break elif clickCounter == 3: print("We're going straight.") break finally: # 程序结束后清理GPIO资源,避免引脚占用 GPIO.cleanup()
关键修改点说明
- 超时时间定义:用常量
CLICK_TIMEOUT统一管理超时时长,方便后续调整 - 起始时间记录:内层循环开始前用
start_time = time.time()记录当前时间戳 - 超时检查:每次内层循环都计算
elapsed_time,一旦超过阈值就打印提示并跳出 - 资源清理:用
try-finally块确保程序结束时一定会执行GPIO.cleanup(),避免Raspberry Pi的GPIO引脚被持续占用 - 提示文本优化:更新了打印提示,明确告知用户有15秒的操作时间
这样修改后,程序就会同时满足“最多3次点击”和“15秒超时”两个跳出条件啦。
内容的提问来源于stack exchange,提问作者Lukakio
相关产品推荐
相关产品推荐

