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 <Servo.h>
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.