I am trying to control my servo to go from 0 degrees to 90 degrees by pressing a button and switch back and forth by pressing the button. But once I press the button to make the servo go to 90 degrees, the servo starts twitching and does not stay in the position. But it will stay put and work fine when it goes to 0 degrees. Any ideas on why this is happening? This is also not my original code. I have little to no experience coding and found this online. Here is the video of the servo.
//Button Toggle Servo
#include <Servo.h>
Servo servo; // create servo object to control a servo
// twelve servo objects can be created on most boards
const int buttonPin = 2;
boolean lastState = LOW;//storage for last button state
boolean pos = true;
void setup()
{
servo.attach(8); // attaches the servo on pin 9 to the servo object
pinMode(buttonPin, INPUT_PULLUP);//this time we will set the pin as INPUT
Serial.begin(9600);//initialize Serial connection
}
void loop()
{
boolean currentState = digitalRead(buttonPin);
if (currentState == LOW && lastState == HIGH)
{
Serial.print(pos ? "up" : "down");
servo.writeMicroseconds(pos ? 1900 : 900);
delay(150);
pos = !pos;
}
lastState = currentState;
}
Robin2:
Are you getting the correct messages printed on the Serial Monitor ?
I am getting correct messages on the Serial Monitor. It just says Starting in the very beginning and doesnt again. But I am still getting the same twitching with my servo.
jremington:
And are you still trying to power the servo from the Arduino?
No. At least I dont think so. I'm not using the 5v pin on the board. I have 4 AA batteries that I have wired to power the servo. Here is a picture of my wiring. Hopefully I didn't mess something up here or else I'm going to feel dumb.
They should be. After doing some research it seems that the servos need a few Amps to work properly. Do 4 AA batteries supply enough Amps to run up to 6 servos? Could that be the problem?
Well I want to eventually power 6 servos for the project. What kind of power system do I need to eventually power 6 servos together? Any suggestions on what I should get?
With LiPo batteries you have to worry about over-discharge, which destroys them, and improper charging, which can cause fires. You need a LiPo charger and the battery should have a protection PCB, plus you will need a voltage regulator to provide 5-6 V at 6 amps for the servos.