I have a project I am working on and when I plug the servo in it just spins constantly in one direction. If I upload a basic sweep program is seems to work fine although I need to unplug the servo from power first otherwise in continues to spin. The only code for the servo is under an if statement so it shouldn't be doing anything unless a button is pressed.
is it necessary to tell the servo to move forward?
MyServo.write(90); is telling this allso I think.
try
if (digitalRead(Push_Button) == LOW) // Is the button being pressed
//myStepper.step(Forward_Rev); // Move the motor forward.
//Make servo go to 90 degrees
MyServo.write(90);
delay(50);
MyServo.write(0);
delay(50);
Made some corrections and added some notes for you. This should solve most of your issues.
#include <Stepper.h>
#include <Servo.h>
int Push_Button = 2;
int Limit_Switch = 13;
//int servo_Pin = 3;
// Create a servo object
Servo MyServo;
// Define the servo pin:
#define servoPin 3 //Using define is frowned upon but if you want to use it thats fine
// Create a variable to store the servo position:
int angle = 0;
const int Steps_Per_Rev = 200;
const float Gear_Reduc = -0.5;
const float Gear_Reduc_Rev = 4;
const float Forward_Rev = Steps_Per_Rev * Gear_Reduc;
const float Backward_Rev = Steps_Per_Rev * Gear_Reduc_Rev;
Stepper myStepper(Steps_Per_Rev, 8, 9, 10, 11);
unsigned long prevTime = millis();
void ForwardRev()
{
int button_state = digitalRead(Push_Button);// Get the button state before you use in the if statement
delay(100);//Delay a bit for debouncing
if ( button_state == LOW) // Is the button being pressed
//If you are going to have multi statements you really need to put them inside brackets
{
myStepper.step(Forward_Rev);
MyServo.write(90);
delay(1500);
MyServo.write(0);
delay(50);
}
}
void BackwardRev()
{
if (digitalRead(Push_Button) == HIGH &&// Is the limit switch pressed.
digitalRead(Limit_Switch) == LOW)
myStepper.step(Backward_Rev); // Move the motor backwards.
}
void setup()
{
myStepper.setSpeed(60);
MyServo.attach(servoPin); // We need to attach the servo to the used pin number
MyServo.write(0);// write the servo to the 0 pos first
pinMode(Limit_Switch, INPUT_PULLUP);
pinMode(Push_Button, INPUT_PULLUP);
}
void loop()
{
unsigned long currentTime = millis();
ForwardRev();
if (currentTime - prevTime > 50) {
BackwardRev();
prevTime = currentTime;
}
}