0

I'm trying to have the return value of a function stored in a variable. The function is called (by a reference) when a Raspberry Pi gpiozero button is pressed.

from gpiozero import Button
from signal import pause

def fcn(a):
    print(a)
    b = a + 1
    print(b)
    return b

btn = Button(26)

i = 1
btn.when_activated = lambda: fcn(i) # returns 2

pause()

When the button is pressed it will print 1 and 2 as expected.

But how can I store the return value of fcn into i so it can increment at each button press?

Edit: The reason I've started with the when_activated reference is that is in my main script I've got multiple buttons and multiple functions which can be pressed in any order and should pass around variables to each other. Something like this:

def fcn(a):
    b = a + 1
    return b

def fcn2(b):
    c = b + 10
    return c

btn1 = Button(26)
btn2 = Button(19)

i = 1
btn1.when_activated = lambda: fcn1(i) # returns i + 1
btn2.when_activated = lambda: fcn2(i) # returns i + 10

Actually I'm also passing around datetime objects.

arjobsen
  • 313
  • 2
  • 12

2 Answers2

0

Assign to i the value of fcn(i) every time the button is pressed:

def fcn(a):
    print(a)
    b = a + 1
    print(b)
    return b

i = 1
while 1:
    input() # Button press
    i=fcn(i) # Incrementation
Rasgel
  • 152
  • 1
  • 1
  • 13
  • Unfortunately I can't do that because I have 3 buttons that can be pressed independently of each other, which call 3 different functions – arjobsen Apr 14 '19 at 10:28
0

Just a fix up. You can use global in your function to assign to i. see the example code below from gpiozero import Button from signal import pause

def fcn():
    global i
    i = i + 1
    check()
    return b #No need of returning


def check():
    print i


btn = Button(26)

i = 1
btn.when_activated = lambda: fcn() # returns 2

pause()

global tells interpreter that variable, in this case "i" is relating to the variable of outer scope. hen you can to anything with that variable... function check() just prints the value for evaluating, so you can remove it.