Home > Blockchain >  How to invoke callback then go back to while loop in Python
How to invoke callback then go back to while loop in Python

Time:12-31

I was hoping someone could help me with the following. I have a raspberry pi with an external button with GPIZero on linux. I would like it so when I press the button, python prints "button is pressed" once, and nothing else prints until I release the button. When the button is released, I'd like for python to print "loop" every three seconds. When I press the button, I always want the latest loop() function to be finished beforehand.

So essentially, upon startup, python should print "loop" over and over again until I press the button. When I press the button the loop() process should finish before python prints "button is pressed". Then as long as I am holding the button, nothing else should print. When I release the button, it should go back to looping "loop".

Right now what I have below doesn't work, but its very close to accomplishing what I want. The issue is this block of code, I believe:

if button.is_pressed:
        if timer ==1:
            button.when_pressed = press

When I press the button with timer=1, I have to press the button a second time (very very quickly) in order for it to run the press() function how I've described. I'd like to hold hold the button once for the press() function to run. I know how its set up is wonky. I believe the button.when_pressed isn't registering that the button is already pressed when it gets to that point in the code. I have to quick hit the button again to get the code to go. I feel like it likes it better when it is not nested in the other button.is_pressed section. However, I don't know what to do. I feel like I need both. I want to keep the button.when_pressed callback because it prints "button is pressed" only once like I want and holds it until I release the button, but I can't get it to work on its own with If -statements. Meanwhile, using only the button.is_pressed while holding the button keeps python looping the "button is pressed" print, which I don't want.

Any help would be appreciated.

#!/usr/bin/python3

from gpiozero import Button
from time import sleep

import time

button = Button(4)
timer = 0

def press():
    print("Button is pressed")

def loop():
    global timer
    timer =  0
    print('loop')
    sleep(3)
    timer = 1

#button.when_released = release

while True:

    if button.is_pressed:
        if timer ==1:
            button.when_pressed = press
            sleep(4)
            button.when_pressed = None

    else:
        loop()

CodePudding user response:

def MainLoop():
    is_pressed = False
    while True:
        if not is_pressed and button.is_pressed:
           is_pressed = True
           do_something()
        else if is_pressed and not button.is_pressed:
           is_pressed = False

just maintain state...

  • Related