Trying to control servo with push button

First of all, I do not have all that much programming experience. I want to control a servo with a button, so that I press the button and it moves the servo in a certain way, but this code will not work for me. I press the button and the servo will go back and forth 4-5 times.

#include <Servo.h>
Servo door;
int button;    
void setup() {
pinMode(4, INPUT);
  
door.attach(9);
door.write(0);
}

void loop() {
 button = digitalRead(4);  
if (button == HIGH) {
delay(10);
     button = digitalRead(4);  
    if (button == HIGH) {
     door.write(180);
     delay(1000);
   door.write(0);
     delay(1000); 
    } 
}
}

Thanks,
Jack

Floating input pin?

Are you saying make the button var a float?

jag3498:
Are you saying make the button var a float?

No, he is saying that button needs either a pull down resistor, a pull up resistor or the code needs to enable the internal pull-up resistor.

No, I'm asking how the switch is connected.

The push button is on a breadboard, with a wire from 5v to the first push button pin, then a wire from the other pin to the 4 pin

In this case, you are missing a pull-down resistor between arduino pin and ground. Use anything between 2K ohm and 40K ohm.

You will want to reverse the logic of your push button so you can use the internal pull-up resistor, so you don't have hook up a resistor.

Works perfectly! Thanks!

You are welcome. I still recommend using the internal pull-up resistor. It's easy. No additional resistors on your breadboard.