# Trying to move a stepper motor back and forth

So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.

I am having some trouble with this though, because while it will move in one direction, it will not move in the other.

``````void setup()
{
stepper1.setMaxSpeed(1000);
stepper1.moveTo(1024);
stepper1.setAcceleration(100);
Serial.begin(19200);
while(!Serial);
}

void loop()
{
stepper1.run();
static int ctr = 0; //counter value to store how many times the back and forth motion has occured
if(stepper1.currentPosition() == 1024){
backMotion(stepper1.currentPosition());
forthMotion(stepper1.currentPosition());
ctr++;
}
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(int value){
int current = value;
int back_distance = current - 200; //distance to move back by
stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
int current = value;
int forth_distance = current+200;
stepper1.moveTo(forth_distance);
}
``````

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop? Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...

Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?

Edit: The code seems to work when I uncomment the if statement in the loop function.

• Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Your current snippet does not reveal which libraries you are using or how you declared and initialized the `stepper1` object. Anyhow, please edit your question to include that information via an MCVE. – James Waldby - jwpat7 Mar 15 '17 at 19:56
• Looks like you are missing a few ` stepper1.runSpeedToPosition();` – Mikael Patel Mar 16 '17 at 18:24
• @MikaelPatel - why do I need the runSpeedToPosition function? – Zaid Humayun Mar 16 '17 at 22:46
• The manual says "Runs at the currently selected speed until the target position is reached". You might want to give the stepper some time to complete the operation. airspayce.com/mikem/arduino/AccelStepper/… – Mikael Patel Mar 16 '17 at 22:54
• You also need to define what "stepper1" is in your scope. – Isaac Turner Jul 23 '19 at 17:33