Search code examples
pythonfunctionwhile-loopraspberry-pigpio

How can I use the gpiozero button.when_pressed function to use a function that inputs and outputs integers?


I'm trying to program a button on a Raspberry Pi to add an integer to another integer so that I can flip back and forth between conditions in a while loop by checking if the variable mod 2 is 0 or not. I'm essentially trying to flip the condition in the while loop by checking whether the variable is odd or even.

I'm trying to use the gpiozero library's when_pressed function, but it doesn't seem to be able to call a function that adds and outputs integers.

So, my code is:

from gpiozero import Button
btn = Button(17) #the button is wired to GPIO pin 17

def addSurf(a):
    a = a + 1
    return(a)

x = 0
btn.when_pressed = addSurf(x)

while True:
    if x == 0:
        #do some stuff
    else:
        #do some other stuff

Why I try to run this, I get TypeError: unsupported operand type(s) for +: 'Button' and 'int'.

How can I use the btn.when_pressed function to use a function that inputs and outputs integers?

Alternatively, is there some other [better?] method to make a button toggle the two states in the while loop?


Solution

  • I realized that the button.when_pressed function can't take any arguments.

    To accomplish my original goal of having the button toggle between two different states in a while loop, I ended up having the button toggle the sign of an integer as a global variable in its own thread in a while loop, and having that sign of the global variable toggle the conditions in another thread in the original while loop. This isn't really a proper way to do it, but I got it working.