Button input coding

Help me out, i have tested all type of combinations of while, else and if during the last 24 hours but can not get it right.
I want to use one button for two functions with a twist.

  1. press it shortly once and make it high and then let it go, write buzPin HIGH
  2. press and hold for lets say 300ms code must break; and continue outside buzPin code.

Well, that is done and completed with below code but when i press button and hold inputPin HIGH to exit buzPin code, it will write buzPin HIGH once more and then wait for inputPin to go low before exiting.

My Twist, when i press button and time is greater then 300ms it will exit but not put buzPin HIGH that last time before waiting for inputPin to go low again.

This is my code.

 while(//anything just to keep loop)  {
  digitalWrite(buzPin, LOW);
  if (digitalRead(inputPin) == HIGH) {
  if (pulseIn(inputPin, HIGH) > 300000) {break;}
  digitalWrite(buzPin, HIGH);
  delay(100);
  }
  }

This code will do the same thing but some times it will complete it with the Twist functionallity i am looking for.

 while(pulseIn(inputPin, HIGH) < 300000)  {
  digitalWrite(buzPin, LOW);
  if (digitalRead(inputPin) == HIGH) {
  digitalWrite(buzPin, HIGH);
  delay(100);
  }
  }

I have tested to play around with the delay time and several debounce codes but no luck. :-[

when i press button and time is greater then 300ms it will exit but not put buzPin HIGH that last time

That's exactly what you have coded in your first example - the break exits the loop, so the digitalWrite call isn't executed. Add another digitalWrite call inside the if block before the break.

-j

-J

Let me explain it in another way.

  1. Push button once, beep sound
  2. Push and hold button, exit the while command without beep sound

Problem is that when i push and hold button it will beep once more before exit the while command.
What did the suggested digitalWrite do in:
if (pulseIn(inputPin, HIGH) > 300000) {break;}

Sorry if i am being slow in my mind :slight_smile:

Warning: this is a bit off the top of my head; it could be total garbage. It assumes logic 1 for a button press.

while (1)
{
  while (!digitalRead(BUTTON))    // wait for button press
    {;}
  start = millis();
  delay(DEBOUNCE_TIME);         // debounce the button press
  while (digitalRead(BUTTON))    // wait for button release
    {;}
  duration = millis() - start;
  if (duration < LONG_BUTTON_PRESS)
    beep();
  else
    break;
}

-j

Thanks for the feedback kg4wsv :slight_smile: