Pushbotton Servo Control

I have been trying to use a pushbutton to control a Vilros microservo to where I press the button, it moves to the 180 degree mark and when I let go, it returns to 90. Whenever I upload it, it spazzes out and moves between two between to different orientations and never stops, and the button doesn’t have any effect. Is there something I am doing wrong, or is there a better way to do this?

#include<Servo.h> //servo library
const int servopin = 13; //assigns the servo to pin 13
const int buttonpin = 12; //assigns the pushbutton to pin 12
int buttonstate = 0; //Pre-sets the button to off
Servo buttonservo; //assigns the servo
void setup() {
pinMode(servopin, OUTPUT); //sets the servo as output
pinMode(buttonpin, INPUT); //sets the pushbutton as input.
buttonservo.attach(servopin); //attaches the servo to the servo pin.
}

void loop() {
buttonstate = digitalRead(buttonpin); //tells the pushbutton to read the button pin.
buttonservo.write(90);
if (buttonstate = HIGH)
{

buttonservo.write(180);
}
else
{
buttonservo.write(90);
}

}

Thanks, any help is appreciated!

How is the switch on pin 12 wired?

if (buttonstate = HIGH)

This makes buttonstate HIGH and since that is not 0 it is always true.

So the servo starts to go to 180 but then loop repeats and the second line of loop sends it back to 90. So it is constantly getting this:

go to 90 go to 180 go to 90 go to 180

only those commands are coming so fast the servo can't get all the way there before being sent back to the other.

= is for assignment == in for comparison

The button is wired with pin 12 on one contact and 5v on the other on the same side.

Electro-Llama: The button is wired with pin 12 on one contact and 5v on the other on the same side.

So when it isn't being pressed, what do you expect the state of pin 12 to be?

It wouldn't be connected to anything, so it is floating. So it could be LOW or HIGH and there's no way for you to control that.

Wire your switch between the pin and ground instead. Use INPUT_PULLUP instead of INPUT in pinMode and a pressed button will be LOW and an unpressed button will read HIGH.

Simple servo button test code.

//zoomkat servo button test 7-30-2011
//Powering a servo from the arduino usually *DOES NOT WORK*.

#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
Servo servo1;

void setup()
{
  pinMode(button1, INPUT);
  servo1.attach(7);
  digitalWrite(4, HIGH); //enable pullups to make pin high
}

void loop()
{
  press1 = digitalRead(button1);
  if (press1 == LOW)
  {
    servo1.write(160);
  }
  else {
    servo1.write(20);
  }
}

Thanks! Will it work while not hooked up to a computer?

Electro-Llama:
Thanks! Will it work while not hooked up to a computer?

Well, that depends.