m5stack / M5Unified

Unified library for M5Stack series
MIT License
330 stars 58 forks source link

Questions about M5.BtnA.releasedFor and M5.BtnA.wasReleaseFor #128

Open patfelst opened 1 month ago

patfelst commented 1 month ago

Hi there, I'm using an M5AtomS3. I need to execute some code only once, about 1500ms after BtnA has been released after being held for some time. When I use if (M5.BtnA.releasedFor(1500)), it does become true 1500ms after being released, but then remains true forever so the code is also executed forever. Is there a way to reset this button status, or do I need to add my own boolean flag to keep track of when the code has been executed so that it only happens once?

Also if I try if (M5.BtnA.wasReleaseFor(1500)) it never seems to be true.

Here is my code:

  // Display the LED brightness while the user adjusts it (or finishes adjusting) in the main loop
  if (M5.BtnA.isHolding() || M5.BtnA.wasReleasedAfterHold()) {
    // Label
    M5.Display.setTextPadding(0);
    M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
    M5.Display.setTextDatum(top_left);
    M5.Display.drawString("LED Brt:", 0, y_pos);

    // Value
    M5.Display.setTextPadding(40);
    M5.Display.setTextColor(TFT_GREEN, TFT_DARKGREY);
    M5.Display.setTextDatum(top_right);
    M5.Display.drawNumber(led_bright, wd - 5, y_pos);
  }
  else if (M5.BtnA.releasedFor(1500)) {
    M5.Display.clear(); // <== Keeps executing over and over 1500ms after user releases button
  }

The following code works but is not as neat as using built in M5 functions

  if (M5.BtnA.isHolding() || M5.BtnA.wasReleasedAfterHold()) {
    relased_ms = millis();
    bright_txt_cleared = false;
    // Label
    ...
    // Value
    ...
  }
  else if (!bright_txt_cleared && millis() - relased_ms > 1500) {
    bright_txt_cleared = true;
    M5.Display.clear(); // <== Executes only once 1500ms after user releases button
  }

thanks for any suggestions!

lovyan03 commented 3 weeks ago

Hello, @patfelst Sorry for the late reply. Are you running the M5.update(); function properly? Calling this function will update the state of all buttons, so you must call it once before reading the button state. If you do not call it or call it more than once, the state will not be updated correctly.

patfelst commented 3 weeks ago

thanks, I will check this soon!