Get the push button sense once

I'm using the push button with the built in pull-up resistor;

pinMode(b1, INPUT_PULLUP);

and have such a main loop. Whenever I press the push button and hold, the empty string called "pass" takes dozens of "1", as expected :slight_smile:
However I want to make it sense the push once until I release it and push again.
By that structure, it is not likely to implement I think.

What would your suggestions be ?

void loop()
{
if(digitalRead(b1) == LOW)
{
pass += "1";
counter += 1;
}
}

You must make a variable that holds the state of the button. Only if the state changes there is action

something like this

int pressed = 0;

void loop()
{
  if (digitalRead(b1) == LOW && pressed == 0)
  {
    pressed = 1;
    pass += "1";
    counter++;
  }
  if (digitalRead(b1) == HIGH && pressed == 1)
  {
    pressed = 0;
  }
}

give it a try

Seems pretty logical but doesn't work.
I've implemented more or less a similar solution but it didn't work either. Strange

robtillaart:
You must make a variable that holds the state of the button. Only if the state changes there is action

something like this

int pressed = 0;

void loop()
{
  if (digitalRead(b1) == LOW && pressed == 0)
  {
    pressed = 1;
    pass += "1";
    counter++;
  }
  if (digitalRead(b1) == HIGH && pressed == 1)
  {
    pressed = 0;
  }
}



give it a try

This code does what I would expect

String pass;
int counter =0;
int pressed = 0;
int b1 = 3;

void setup()
{
  pinMode(b1, INPUT_PULLUP);
  Serial.begin(9600);
}
void loop()
{
  if (digitalRead(b1) == LOW && pressed == 0)
  {
    pressed = 1;
    pass += "1";
    counter++;
    Serial.println(pass);
  }
  if (digitalRead(b1) == HIGH && pressed == 1)
  {
    pressed = 0;
  }
}

Sample output of 4 button presses

1
11
111
1111

NOTE - no debounce implemented but the button action seems relatively snappy so not a problem

1
11
111

at 1 press. Very snappy :confused:
What can I do ?

Debounce the button by the look of it.

And maybe look for a button state change.