Hold button for a duration

Hi,

I have a project where I need a button press held a little longer (i.e. 1-2 seconds) to ensure the relay triggers my door to open - anything shorter and the relay triggers, but it is too brief to trigger the door.

The current working code is below, and I have seen instances where timer.setTimeout is used but I don’t understand how to use it in the below code:

BLYNK_WRITE(V0)
    {
      int pinValue = param.asInt();
      if (pinValue == 5) {
            const byte RelayON[] = {0xA0, 0x01, 0x01, 0xA2};
            Serial.write(RelayON, sizeof(RelayON));
         }else {
            const byte RelayOFF[] = {0xA0, 0x01, 0x00, 0xA1};
            Serial.write(RelayOFF, sizeof(RelayOFF));
        }
    }

Look at the old fashioned debouncing code for buttons and try to adapt that

Are you using a segmented switch or a button?

I am curious as to why you use 5 instead of 1?

param.asInt == ‘5’

Edit:

Either way, try this?:

BLYNK_WRITE(V0)
 {
  int pinValue = param.asInt();
  if (pinValue == 5) {
        const byte RelayON[] = {0xA0, 0x01, 0x01, 0xA2};
        Serial.write(RelayON, sizeof(RelayON));
    timer.setTimeout(1500L, []() {
        const byte RelayOFF[] = {0xA0, 0x01, 0x00, 0xA1};
        Serial.write(RelayOFF, sizeof(RelayOFF));
    });
     }
}

You will also need to declare:

BlynkTimer timer;

And this in void loop()

timer.run();
1 Like

Video_2019-05-13_181245 2019-05-13_183235

/**************** LOCK UNLOCK **************/
BLYNK_WRITE(V50) {  // button to be held down to activate
    if (param.asInt() and  !LongHold ) {
    ButtonTimer = timer.setTimeout(2000, LongHoldDetect); // press 2 sec
    ButtonPressed = true;
    
// Button has been released
  } else {
    ButtonPressed = false;        // Reset press flag
 
    // If the long hold function wasn't called, it's a short press.
    if (!LongHold) {
      timer.deleteTimer(ButtonTimer);   // Kill the long hold timer if it hasn't been activated.

      // Reset the long press flag
      LongHold = false;
      greenLed.off();
      redLed.on();
    }
  }
}

// Checks for long press condition on SETTINGS button
void LongHoldDetect() {
  // If the button is still depressed, it's a long hold
  if (ButtonPressed) {
    LongHold = true;
    greenLed.on();
    redLed.off();
     }
}

BLYNK_WRITE(V51) {  // Reset button
  if (param.asInt()) {
    if (LongHold = true) {
      ButtonPressed = false;
      LongHold =  false;
      greenLed.off();
      redLed.on();
        }
  }
}
2 Likes