Push button controlling servo loop Issue

hello,

I am trying to control a servo using a push button to make the servo rotate from 180 degrees to 120, then back again after the pushbutton is pushed 1 time. After this I would like the If loop to stop running and wait for the button to be pressed again. My code works, however after the button is pressed the servo loops from 120 to 180 over and over again. How can I set up my If statement to return the input signal back to low? Or is there a better way to write the code?

#include <Servo.h> 

Servo myservo;

int testPIN = 13;
int inputPIN = 2;
int val=0;
int state=0;
int old_val = 0;
void setup() 
{ 
  myservo.attach(9);
  pinMode(testPIN, OUTPUT);
  pinMode(inputPIN, INPUT);
} 

void loop() {


 
  val = digitalRead(inputPIN);
  if ((val == HIGH) && (old_val == LOW)){
   state = 1-state;
   delay(10);
  }
  
  old_val = val;
  
   if (state==1) {
   digitalWrite(testPIN, HIGH);
myservo.write(120); 
delay(10);

digitalWrite(state,1);
digitalWrite(old_val,LOW);
digitalWrite(val,LOW);
delay(10);
  }else {
    digitalWrite(testPIN,LOW);
    myservo.write(180);
  }

}

Thanks

Have you an external pull-down resistor on your input pin?
It is probably easier to use pinmode(inputPin, INPUT_PULLUP); and arrange for the switch to connect the pin to GND when pressed. That would require you to invert your test to if ((val == LOW) etc

...R

    digitalWrite(state, 1);
    digitalWrite(old_val, LOW);
    digitalWrite(val, LOW);

Whatever else might be going on what are these lines of code meant to do ?

After this I would like the If loop to stop running and wait for the button to be pressed again.

Have you ever considered looking at the examples? The State Change Detection example comes to mind.

The digitalWrite lines were my attempt to change the state of the button back to low so it only looped once. I have looked at most of the examples for push button start, but i will look into the state change detection. Robin2, I am not sure what type of resistors I am using in that sense, I just have a 10K ohm resistor in series with the button. I think I see where you are going with the pin to ground. Ill give that a shot.

digitalWrite on an input pin just turn off & on the internal pullup resistor.
What I do is note the time the button was pushed, note the time it was next pushed, and if not long enough had lapsed to ensure good debouncing, I ignore it. Say 200mS
If was long enough, then react to it. This also allows for push & hold to advance a time display for instance at a rate of 5 ticks per second with enough debounce time to release and have it stop where you want.
This could also be recognized as a takeoff of blink-without-delay.