简体   繁体   English

如何使用Raspberry Pi上的按钮在while循环中切换状态?

[英]How do I use a button on a Raspberry Pi to toggle states in a while loop?

I'm trying to figure out a way to use a button on a Raspberry Pi to toggle between two different conditions in a while loop. 我试图找出一种方法来使用Raspberry Pi上的按钮在while循环中在两个不同的条件之间切换。 Ideally, by merely pressing the button, I could switch back and forth. 理想情况下,只需按下按钮,我就可以来回切换。

I know this is wrong, but I'm not sure where to go from here. 我知道这是错的,但我不知道从哪里开始。

Roughly, my code looks like this: 粗略地说,我的代码看起来像这样:

from gpiozero import Button

btn=Button(17) #The GPIO pin is 17

def addSurf():
    i = i + 1

i = 0

btn.when_pressed = addSurf

while True:
    if i % 2 == 0:
        #do some stuff
    else:
        #do some other stuff

Since I started i at 0 before the while loop, I figured that by adding integers when the button was pressed, and checking to see if the modulo was zero or not, I could navigate back and forth between the two states. 自从我开始i在0之前while循环,我想通过添加整数按下按钮时,并检查是否模数是零或没有,我可以导航来回在两种状态之间。

However, I don't know how to incorporate the .when_pressed function into the loop so that it's always going to respond to move the program into one state or the other. 但是,我不知道如何将.when_pressed函数合并到循环中,以便它总是响应将程序移动到一个状态或另一个状态。

Forgive me if I'm a bit of a newbie here, but I tried looking into the documentation for raspberry-gpio-python for information about event detection and multithreading, but I didn't understand it. 请原谅我,如果我在这里有点新手,但我尝试查看raspberry-gpio-python的文档,了解有关事件检测和多线程的信息,但我不明白。

It turns out that the problem with the button.when_pressed function is that it can't take any argument, so there's no way to have it act as a variable. 事实证明, button.when_pressed函数的问题在于它不能接受任何参数,因此没有办法让它充当变量。

Though it may not be the proper way to do it, I ended up running two different while loops in their own threads and having the button.when_pressed function toggle the sign of an integer in a global variable, as as a kind of switch for the other thread. 虽然它可能不是正确的方法,但我最终在他们自己的线程中运行了两个不同的while循环并且使用button.when_pressed函数切换全局变量中整数的符号,就像一种开关用于其他线程。

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

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