LennartHennigs / Button2

Arduino/ESP button library that provides callback functions to track single, double, triple and long clicks. It also takes care of debouncing.
MIT License
487 stars 81 forks source link

Change pin assignments at runtime #31

Closed melkati closed 2 years ago

melkati commented 2 years ago

Hi.

Thank you very much for your library. Fantastic, a time saver!

I'm using it on a project (a CO2 monitor) and I'm adding the possibility to reverse the display 180º with a menu option. In a board like the TTGO T-Tdisplay, when display is reversed I need also to reverse the functionality of the two buttons it has.

Until now I was initializing buttons as:

Button2 btnUp(BTN_UP);   // Initialize the up button
Button2 btnDwn(BTN_DWN); // Initialize the down button
void buttonsInit() {
  btnUp.setLongClickTime(LONGCLICK_TIME_MS);  
  btnUp.setLongClickHandler([](Button2 &b) { nav.doNav(enterCmd); });
  btnUp.setClickHandler([](Button2 &b) {
    // Up
    nav.doNav(downCmd);
  });

  btnDwn.setLongClickTime(LONGCLICK_TIME_MS);
  btnDwn.setLongClickHandler([](Button2 &b) { nav.doNav(escCmd); });
  btnDwn.setClickHandler([](Button2 &b) {
    // Down
    nav.doNav(upCmd);
  });
}

https://github.com/melkati/CO2-Gadget/blob/8b55114596b1c5b811b091d794e3dccd75928657/CO2_Gadget_Buttons.h#L17-L34

What is the best way to "reverse the buttons" at execution time, so now btnUp is assigned to pin BTN_DWN (instead of BTN_UP) and btnDwn to pin BTN_UP (instead of BTN_DWN)?

LennartHennigs commented 2 years ago

Hey, it's a bit dirty but I think you should be able to "switch" pins by calling begin() on each button with a new pin number as it does not remove all the handlers when called.

melkati commented 2 years ago

Hi.

Thank you.

Finally I created a specific function to reverse buttons. I left it here just in case anyone has this need (specially with so many people utilizing the library AndroidMenu with Buttons2).

void reverseButtons(bool reversed) {
  if (reversed) {
    // Interrupt Service Routine to turn on the display on button UP press
    attachInterrupt(BTN_UP, buttonUpISR, RISING);
    btnDwn.setLongClickTime(LONGCLICK_TIME_MS);
    btnDwn.setLongClickHandler([](Button2 &b) { nav.doNav(enterCmd); });
    btnDwn.setClickHandler([](Button2 &b) {
      nav.doNav(downCmd);
    });

    btnUp.setLongClickTime(LONGCLICK_TIME_MS);
    btnUp.setLongClickHandler([](Button2 &b) { nav.doNav(escCmd); });
    btnUp.setClickHandler([](Button2 &b) {
      nav.doNav(upCmd);
    });
  } else {
    attachInterrupt(BTN_DWN, buttonUpISR, RISING);
    btnUp.setLongClickTime(LONGCLICK_TIME_MS);
    btnUp.setLongClickHandler([](Button2 &b) { nav.doNav(enterCmd); });
    btnUp.setClickHandler([](Button2 &b) {
      nav.doNav(downCmd);
    });

    btnDwn.setLongClickTime(LONGCLICK_TIME_MS);
    btnDwn.setLongClickHandler([](Button2 &b) { nav.doNav(escCmd); });
    btnDwn.setClickHandler([](Button2 &b) {
      nav.doNav(upCmd);
    });
  }
}

Full code here