Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect short and long presses from multiple buttons #20

Open
bertenvdb opened this issue Apr 20, 2023 · 0 comments
Open

Detect short and long presses from multiple buttons #20

bertenvdb opened this issue Apr 20, 2023 · 0 comments

Comments

@bertenvdb
Copy link

I want to detect short and long presses from 5 buttons, but this doesn't work good at all.
Is this a limitation of the library, or is it my code?

#include <Arduino.h>
#include <ezButton.h>

struct buttonData
{
  buttonData(int pin) : button(pin, INPUT){};
  unsigned long pressedTime = 0;
  unsigned long releasedTime = 0;
  bool isPressing = false;
  bool isLongDetected = false;
  ezButton button;
};

const int BUTTON_NUM = 5;
buttonData buttons[] = {
    buttonData(39),
    buttonData(35),
    buttonData(33),
    buttonData(34),
    buttonData(14),
};

const int SHORT_PRESS_TIME = 1000;
const int LONG_PRESS_TIME = 1500;

void handle_shortPress(int buttonNumber) {}

void handle_longPress(int buttonNumber) {}

void setup()
{
  Serial.begin(115200);
  Serial.println("Starting");

  for (byte i = 0; i < BUTTON_NUM; i++)
  {
    buttons[i].button.setDebounceTime(50);
  }
}

void loop()
{
  for (byte i = 0; i < BUTTON_NUM; i++)
    buttons[i].button.loop();

  for (byte i = 0; i < BUTTON_NUM; i++)
  {
    if (buttons[i].button.isPressed())
    {
      buttons[i].pressedTime = millis();
      buttons[i].isPressing = true;
      buttons[i].isLongDetected = false;
    }

    if (buttons[i].button.isReleased())
    {
      buttons[i].isPressing = false;
      buttons[i].releasedTime = millis();

      long pressDuration = buttons[i].releasedTime - buttons[i].pressedTime;

      if (pressDuration < SHORT_PRESS_TIME)
      {
        Serial.print("Short press button ");
        Serial.println(i);
        handle_shortPress(i);
      }
    }

    if (buttons[i].isPressing == true && buttons[i].isLongDetected == false)
    {
      long pressDuration = millis() - buttons[i].pressedTime;

      if (pressDuration > LONG_PRESS_TIME)
      {
        Serial.print("Long press button ");
        Serial.println(i);
        handle_longPress(i);
        buttons[i].isLongDetected = true;
      }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant