Time between button press and release in python?
Question: I am trying to time from the start of a button press to the end of a button
press on GPIO (in order to differentiate between a long press and a short
press). I want to use a callback to get the button presses immediately and
without polling. Here is what I tried first:

    
    
    import RPi.GPIO as GPIO
    import time
    
    def my_callback(channel):
        start = time.time()
        GPIO.add_event_detect(25, GPIO.FALLING)
        end = time.time()
        elapsed = end - start
        print(elapsed)
    
    GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
    
    #while other stuff is running
    

On running this program I get:

> RunTimeError: Conflicting edge detection already enabled for this GPIO
> channel.

Because I can't poll both I tried:

    
    
    def my_callback(channel):
        GPIO.remove.event.detect(25)
        start = time.time()
        GPIO.add_event_detect(25, GPIO.FALLING)
        end = time.time()
        elapsed = end - start
        print(elapsed)    
    
    GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
    

This worked once but was not repeatable because I am removing the event
detection and redefining it. Thus I tried to restore the event detect in the
callback:

    
    
    def my_callback(channel):
        GPIO.remove.event.detect(25)
        start = time.time()
        GPIO.add_event_detect(25, GPIO.FALLING)
        end = time.time()
        elapsed = end - start
        print(elapsed) 
        GPIO.remove.event.detect(25)   
        GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
    
    GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
    

This finally worked, but will crash my pi quickly, as I think I created a
loop-back. Is there another way to accomplish this that I am overlooking?


Answer: Thanks to jDo here is the code that works

    
    
    def my_callback(channel):
        global start
        global end
        if GPIO.input(25) == 1:
            start = time.time()
        if GPIO.input(25) == 0:
            end = time.time()
            elapsed = end - start
            print(elapsed)
    
      GPIO.add_event_detect(25, GPIO.BOTH, callback=my_callback, bouncetime=200) 
    

