Button Save State static values

i apologize if this question has been asked, but I can't find an answer that suits my needs. i am simply attempting to save the state of a button and only have values printed to serial monitor when it is pressed. (no scrolling of zeros or ones, just one value).

for example, once it is pressed and released, then it prints a '1' and it remembers the state. then, when I press the button again, it prints a '0' to the monitor.

This should be straightforward. I posted about doing this with an analog potentiometer and tried to transpose that code to this functionality, but it seems I am missing something. Thank you again.

//variables
const int buttonPin = 2;

boolean lastButtonState = 0;
boolean currentButtonState = 0;
char keys[] = {'1', '2'};


void setup() {
  Serial.begin(115200);
  pinMode(buttonPin, INPUT); //declare pushbutton as input
}

void loop() {
  if (lastButtonState != currentButtonState) {
    Serial.println(keys[0]);
  }
  else {
    Serial.println(keys[1]);
  }
  lastButtonState = currentButtonState;
}

You never actually read the pin/switch, only to print it :wink:

for example, once it is pressed and released, then it prints a '1' and it remembers the state.

What do you mean by "remembers the state"? A switch is either pressed or released. "Once a switch is pressed and released", it's state is released. That is not hard to remember. But, it is unnecessary to do so, since it is easy to discover that it's state is released.

If you are looking to do something only when the switch changes from released to pressed, or from pressed to released, the state change detection example shows how to do that.

Of course, the real problem with your code is that you never actually read the state of any switch, so you have nothing to use for the current state that bears any relationship to the switch.