Button2 icon indicating copy to clipboard operation
Button2 copied to clipboard

detection of long presses does not work properly inside of an interupt timer

Open EtoTen opened this issue 2 years ago • 2 comments

FYI, as you predicted when using this library inside an interrupt timer on an esp32, it seems to fail to detect long clicks. Every click, long or short, irregardless of .setLongClickTime() is detected as a long click. I haven't delved into why this behaviour is being exhibited but was able to create a quick work around by capturing the start and stop time of the button presses / release within my own application.

Here is a snippet:

#define MODE_BUTTON  35

Button2 buttonMode;
hw_timer_t *mButtonTimer = NULL;

void IRAM_ATTR buttonTimer()
{
  // process buttons
  buttonMode.loop();
}

setup() 
{
  mButtonTimer = timerBegin(0, 80, true);
  timerAttachInterrupt(mButtonTimer, &buttonTimer, true);
  timerAlarmWrite(mButtonTimer, 10000, true); // every 0.1 seconds
  timerAlarmEnable(mButtonTimer);

  buttonMode.begin(MODE_BUTTON, INPUT, false);
  buttonMode.setLongClickHandler(longModeClickStart);
  buttonMode.setLongClickDetectedHandler(longModeClickStop);
}


long modeStart;

void longModeClickStart(Button2 &btn)
{
  modeStart = micros();
}

void longModeClickStop(Button2 &btn)
{
  int secondsSinceLast = round((micros() - modeStart) / 1000000);
  Serial.print("Seconds since last mode press: ");
  Serial.println(secondsSinceLast);
  if (secondsSinceLast > 20)
  {
   Serial.println("doing something after 20 seconds");
  }
}

EtoTen avatar Jan 06 '23 11:01 EtoTen

Hey Nickolai, thank you for raising the issue! And of course, it doesn't! After thinking about it for a minute over coffee: I use millis() inside my code. 🤦 That's at least one reason without looking into the code. I will take a look at it in the next couple of days.

LennartHennigs avatar Jan 07 '23 10:01 LennartHennigs

To everyone trying this out: do this at your own risk! Using this inside interrupt function may very likely not work. This library was not designed to be used inside interrupts.

LennartHennigs avatar Jun 21 '23 13:06 LennartHennigs