-1

I have made a circuit in which a buzzer buzzes when a button is pressed. It works fine if I use a while loop and continuously detect button state. AFAIK, this is not an efficient way and I should use callbacks.

This works

mport RPi.GPIO as GPIO import time

try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(11,GPIO.OUT)
        GPIO.setup(12,GPIO.IN,pull_up_down=GPIO.PUD_UP)
        
        while True:
                if(GPIO.input(12) == GPIO.LOW):
                        GPIO.output(11,GPIO.HIGH)
                else:
                        GPIO.output(11,GPIO.LOW)
                time.sleep(0.01)
except KeyboardInterrupt:
        GPIO.cleanup()

I am not able to write equivalent code using add_event_detect

This code doesn't work

import RPi.GPIO as GPIO
import time

def handle_button_press_event(button_pin):
        print('button pressed for pin ',button_pin)
        if(GPIO.input(12) == GPIO.LOW):
                GPIO.output(11,GPIO.HIGH)
        else:
                GPIO.output(11,GPIO.LOW)

try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(11,GPIO.OUT)
        GPIO.setup(12,GPIO.IN,pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(12,GPIO.FALLING,callback=handle_button_press_event,bouncetime=5)
        while True:
                time.sleep(0.01)
except KeyboardInterrupt:
        GPIO.cleanup()

What is the way to use callbacks and do an operation when only for the time when the button is pressed. The operation should stop when the button is released.

1 Answer 1

0

You are asking the system to check for falling events (transition from high to low) when you set up the callback.

You need to check for rising and falling events. Use GPIO.BOTH rather than GPIO.FALLING.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.