Servo keeps acting up! Please Review My Code!

Goal:

When a pushbutton is held down, servo goes to 90 degrees. When pushbutton is let go, servo goes to 0 degrees.

Code:

#include <Servo.h>
const int button = 7;
Servo aservo;

int val = 0;
void setup() {
pinMode(button,INPUT);
aservo.attach(9);
}

void loop() {

val = digitalRead(button);

if (val==HIGH){

aservo.write(0);
delay(500);
}
else
{

aservo.write(90);
delay(500);
}

}

Problem:

When the button is let go and left alone, the servo randomly switches degrees. I changed the servo and microcontroller, but same thing happens.

Something isn't wired right. Can you show how it's hooked together?

Floating input pin?

Hi, Welcome to the forum.

Please read the first post in any forum entitled how to use this forum. http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code. It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks... Tom.. :)

Read this about how to wire up push buttons correctly.
http://www.thebox.myzen.co.uk/Tutorial/Inputs.html