Servo start to turn like madman with simple if statement I tried to write a simple program. Press button 1 servo goes to position 1, press button 2 servo goes to position 2. 

But when I hook everything up my Servo goes full Crazy mode. It starts to jiggle back and forth like a madman. Even when I unhook the buttons. 

What is the mistake I made? Any help is appreciated :D

Thanks in advance



/* Sweep
     by BARRAGAN &lt;http://barraganstudio.com&gt;
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep

    modified 5-12-2017
*/

#include &lt;Servo.h&gt;

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);         // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == HIGH) {
    myservo.write(173);        // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == HIGH) {
    myservo.write(97);         // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
}
Please, connect the buttons to the ground and change the code:


#include &lt;Servo.h&gt;

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == LOW) {
    myservo.write(173);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == LOW) {
    myservo.write(97);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
}


Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.