Read the Pushbutton’s State Change

int lastButtonState = LOW;    // state of the button last time you checked
 
void setup() {
  // make pin 2 an input:
  Serial.begin(9600);
  pinMode(2, INPUT);
}
 
void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(2);
  Serial.println(buttonState);
 
  // check if the current button state is different than the last state:
  if (buttonState != lastButtonState) {
    Serial.println("changed");
     // do stuff if it is different here
  }
 
  // save button state for next comparison:
  lastButtonState = buttonState;
}
00:07:27.067 -> 0
00:07:27.067 -> 0
00:07:27.067 -> 0
00:07:27.067 -> 1
00:07:27.067 -> changed
00:07:27.102 -> 0
00:07:27.102 -> changed
00:07:27.102 -> 0
00:07:27.102 -> 0
00:07:27.102 -> 0
00:07:27.102 -> 1
00:07:27.102 -> changed
00:07:27.139 -> 0
00:07:27.139 -> changed
00:07:27.139 -> 0
00:07:27.139 -> 0
00:07:27.139 -> 1
00:07:27.139 -> changed
00:07:27.139 -> 0
00:07:27.139 -> changed
00:07:27.175 -> 0
00:07:27.175 -> 0
00:07:27.175 -> 0
00:07:27.175 -> 1
00:07:27.175 -> changed
00:07:27.175 -> 0
00:07:27.175 -> changed
00:07:27.230 -> 0
00:07:27.230 -> 0
00:07:27.230 -> 0
00:11:42.196 -> changed
00:11:42.196 -> LOW -> HIGH
00:11:42.548 -> changed
00:11:42.548 -> HIGH -> LOW
00:11:43.198 -> changed
00:11:43.232 -> LOW -> HIGH
00:11:43.952 -> changed
00:11:43.990 -> HIGH -> LOW
00:11:43.990 -> changed
00:11:43.990 -> LOW -> HIGH
00:11:44.027 -> changed
00:11:44.027 -> HIGH -> LOW