Why does my servo twitch and turn on its own? I've been trying to write a very simple program using Arduino to tell a servo to go to a specific angle when a button is pressed, and to another specific angle when it is released. I find that, even though my sketch is but the simplest possible if then else statement without anything added to it, the servo goes to the right angle when the button is pressed, but when it is released, the servo oscillates between the two specified angles at a regular rate (about once every second). What's even stranger is that when i add delay time to the end of the loop in my sketch, the oscillation becomes more like twitching, and the more delay i add the weirder and less predictable the twitching becomes.

added info

#include &lt;Servo.h&gt; 
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup() 
{ 
    Servo1.attach(11); 
} 

void loop() 
{ 
    switchState = digitalRead(switchPin);
    if (switchState == HIGH) { 
        Servo1.write(40); 
    } else { 
        Servo1.write(70); 
        delay(39); 
    } 
} 


the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.
If it does what you expect when the button is pressed, but behaves unpredictably when released, you almost certainly have a floating input.

See Switches tutorial.

In particular, this is a no-no:



Random fluctuations in voltages will make the switch read HIGH and then LOW, and your servo will chase around trying to change positions.

The simplest fix (without changing anything else) is to add a pull-down resistor between the pin and ground, so now the pin reliably reads LOW when not pressed.



Other methods are discussed on that page, including debouncing.