Servo moves without button press

I have a servo set up to move at the press of a button. When powered up and with the Arduino turned on, the servo moves back and forth. It seems like it's moving to the positions it's supposed to, but without the button press. When I press and hold the button, it eventually stops, and then everything works as its supposed to. Is there a way to stop it from moving before the button is pressed?

#include <Servo.h>

const int buttonPin = 9;

Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(12);
  pinMode(buttonPin, INPUT);
}

void loop() {
  int buttonState;
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    for (pos = 0; pos <= 180; pos += 1) {
      // in steps of 1 degree
      myservo.write(pos);
      delay(15);
    }
    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
}

Set up your button pin as:

pinMode(buttonPin, INPUT_PULLUP);

and try again.

The button is wired with 1 terminal going to ground, and the opposite terminal going to pin 9 on the Arduino, as well as a to 3.3V with a 10K resistor between.

I'm not using the built-in pull-up resistors, because I don't know what they are, or how to use them.

I set the button pin to INPUT_PULLUP, but nothing changed.

It's an Arduino Uno.

I read a tutorial about hooking up buttons, and it said to use 3.3V. I changed it to 5V, and it doesn't make anything different happen.

I'm using this servo Pololu FS5103B

I basically followed this, except I'm using pin 9 instead.

I think you have the switch wired wrong. Move the black wire to the other side of the switch (shouldn't matter which terminal but for my OCD, use the terminal across the yellow wire.)

You need to common ground the servo power and the Arduino

with ground.GIF

Thanks for your help guys. Next time I’ll definitely include the picture right away.

browntastic:
Thanks for your help guys.

Did it fix the problem though?

You definitely need the common ground, was certainly wrong without it, but was it the problem here, not just a problem?

It did fix the problem. Thanks again.