Not sure if this is a redundant question or what, but I've been messing with this code for half an hour and I just cant seem to get it to work. I have checked examples in the Arduino Projects Book, mainly the ones involving servos and pushbuttons, and they don't seem to be any different than my code (other than the fact that I'm merging the two examples).
The problem is that when I run the code, the servo first jolts about 10-20 degrees (I've heard this is common), then turns all the way to the maximum amount (180), and appears to be continuing to turn, or attempting to turn. Keep in mind that this is all before I even press the button. When I do press the pushbutton, the servo jolts past the 180 degrees by about 10 degrees, then my computer flashes an error message stating that the connected USB device is consuming too much power, and that the computer has cut off its power to the USB port in order to protect its components. Also, when I attempted to turn the servo manually while the code was running, I met heavy resistance from the servo (obviously I stopped trying further).
Heres the code:
#include <Servo.h>
Servo myServo;
int switchState = 0;
void setup()
{
myServo.attach(3);
Serial.begin(9600);
pinMode(13, INPUT);
}
void loop()
{
while(1 == 1)
{
myServo.write(0);
//^added this to make sure that the servo was at 0 when the program started
delay(50);
switchState = digitalRead(13);
if(switchState == LOW)
{}
//^also added this to try to fix it
else if(switchState == HIGH)
{
Serial.println("Button Pressed");
myServo.write(160);
//^changed from 179 just to try to make it more stable
delay(50);
}
}
}
If you think the problem is in the circuitry- It's really just a servo (yes all three wires are connected to the right places) with a capacitor and a pushbutton with an input wire to port 13- then I can post a more detailed description/image, but I really don't think that's the problem. From my limited perspective, the problem appears to be with the if statement checking for the button press, but I can't see any syntax that is incorrect. I hope someone else who is more experienced can solve this.
Btw, the parts I am using are all part of the Arduino Starter Kit, including the servo, and in case it's not clear, I want the servo to turn from 0 degrees to 180 when the button is pressed. Thanks!