简体   繁体   English

按下按钮时在循环中退出

[英]Exit while loop when button is pressed

I'm currently working on a Python/Raspberry Pi game with some LEDS and one switch. 我目前正在开发带有一些LED和一个开关的Python / Raspberry Pi游戏。 I'm trying to exit a loop when a button is pressed and see which LED stays open, the problem is that the way I'm doing it right now doesn't work. 我试图在按下按钮时退出循环,看看哪个LED保持打开状态,问题是我现在的操作方式不起作用。 Any ideas on how to exit the loop when there's the input from the button. 有按钮输入时如何退出循环的任何想法。

EDIT: I want to be able to exit the loop while the script is sleeping. 编辑:我希望能够在脚本休眠时退出循环。

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(6,GPIO.OUT)
GPIO.setup(26,GPIO.IN,pull_up_down = GPIO.PUD_UP)
def check():
    input_state = GPIO.input(26)
    if input_state == False:
        break
while True:
    GPIO.output(6,GPIO.HIGH)
    check()
    time.sleep(0.5)
    check()
    GPIO.output(6,GPIO.LOW)
    GPIO.output(19,GPIO.HIGH)
    check()
    time.sleep(0.5)
    check()
    GPIO.output(19,GPIO.LOW)
    GPIO.output(13,GPIO.HIGH)
    check()
    time.sleep(0.5)
    check()
    GPIO.output(13,GPIO.LOW)
GPIO.cleanup()

You have the logic backwards; 你的逻辑倒退了。 when you do get a keypress 26, you want to exit. 确实有按键26时,您要退出。 Also, the break must be inside the loop: yours is off in a function, where all you can "break" is the function. 同样, break 必须 循环内部 :函数关闭了您的中断,而您只能“中断”该函数。 Instead ... 相反...

def check():
    input_state = GPIO.input(26)
    return input_state

while True:
    GPIO.output(6,GPIO.HIGH)
    if check():
        break
...

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

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