r89m/Button

Using the library with Interrupt Input.

Opened this issue · 1 comments

Dear Concerned,
I have been using this library for the last few years and found its performance very much satisfying.
I am now in need to use interrupt along with this library but unfortunately could not find any way through.

Could you please help me achieve this. I am using ESP8266 with hardware interrupt.

Awaiting prompt response please.

Sarwar

r89m commented

Hi Sarwar,

I'm glad you've found this library useful.

I've not used interrupts in a long time but I do seem to remember that it is encouraged not to do too much processing within the interrupt handler. To that end I'd suggest implementing a new InterruptButton that extends Button with a flag that can be set by the interrupt handler. You can then check this flag at regular intervals within your code so that the event handler can be fired as soon as possible.

It might look something like this (this was written in the comment field, I've not tried to compile it)

class InterruptButton : public Button {
public:
    void interruptHandler() {
        // TODO: Handle debouncing...
        interruptTriggered = true;
    }

protected:
    boolean _update_button_state() override {
        if (interruptTriggered) {
            interruptTriggered = false;
            return true;
         } else {
            return false;
         }
    }
private:
   bool interruptTriggered = false;

};

// Somewhere else in your code....
ESPRegisterInterruptHandler(myButton.interruptHandler);

You would then call myButton.update() frequently within your code so that the handler could be fired as soon as possible, for example:

void loop() {
    myButton.update();
    my_slow_function_that_makes_me_miss_button_presses();
    myButton.update();
    my_other_slow_function();
    myButton.update();
    another_slow_function();
    myButton.update();
    }

This wouldn't necessarily make your button callback fire quicker, but at least button presses would not be missed.

As I said before, you could call the handler inside the interrupt but I think that this is not recommended.

You may have to read up on how to handle debouncing with an interrupt based switch.
You may also have to mark the interruptTrigger variable as editable from an interrupt handler - volatile perhaps? I'm not sure.

Let me know if there's anything else I can help with.