igorantolic / ai-esp32-rotary-encoder

Easy implement rotary encoder to your application using microcontroler like ESP32
GNU General Public License v2.0
284 stars 70 forks source link

Code for Long press-hold #64

Closed Hoogkamer closed 7 months ago

Hoogkamer commented 1 year ago

In one of the examples there is code explaining for a long press. However that only works after you release the button. I wanted a press-hold function to for example switch off a radio. If anyone is looking for that, here is the code. longPressAfterMiliseconds is a global variable stating how long you need to press before it is triggered.

void handleTunerButton()
{
  static unsigned long buttonPressedTime = 0;
  static bool isLongpress = false;
  bool isEncoderButtonDown = rotaryTuner.isEncoderButtonDown();
  if (isEncoderButtonDown)
  {
    if (!buttonPressedTime)
    {
      buttonPressedTime = millis();
    }

    if (!isLongpress && (millis() - buttonPressedTime >= longPressAfterMiliseconds))
    {
      onTunerLongClick();
      isLongpress = true;
    }
  }
  else
  {
    if (buttonPressedTime && !isLongpress)
    {
      onTunerShortClick();
    }
    buttonPressedTime = 0;
    isLongpress = false;
  }
}
igorantolic commented 7 months ago

Not an issue but another option. Issue is closed. To participate you can add a new example to code.