1

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. 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.

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.

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.

user260467
  • 165
  • 1
  • 9
  • Documentation for the library you use is at https://gpiozero.readthedocs.io/en/stable/recipes.html#button . By default, as it uses python threading library it should automatically fire that function when you are in while loop. You can also check python signal library. – Emin Mastizada Mar 10 '17 at 05:45
  • For anyone who finds this in the future, they may find it helpful to know that I wasn't even printing the output of `addSurf()`, which made it so that the code posted wouldn't work at all. A great explanation is here: http://stackoverflow.com/a/41369646/3956820 – user260467 Mar 10 '17 at 16:27

1 Answers1

0

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.

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.

user260467
  • 165
  • 1
  • 9