Problem with using accelstepper library

Hello all,
I am working on a project where I have to make a motor move for a certain number of steps then stop. I know how to make it move but I dont know how to make it stop. it just keeps going on and on, can someone help me make it stop?

thanks

#include <AccelStepper.h>

AccelStepper motor(1,2,3); // step pin = 2 dir pin = 3
double velocity=900;
double distance=5000;
double acceleration=1000;
int mode=2;

void setup() 
{    
        Serial.begin(9600); 
}

void loop() 
{
  if (mode==1)
  {
     motor.setCurrentPosition(0);  
     moveup();
  }
  if (mode==2)
  {
     motor.setCurrentPosition(0);  
     movedown();
  }
}

void moveup()
{
  while(mode==1)
  {
    motor.setMaxSpeed(velocity);
    motor.setAcceleration(acceleration);
    motor.move(-distance);
    motor.run();
  }    
}


void movedown()  
{
  while(mode==2)
  {
    motor.setMaxSpeed(velocity);
    motor.setAcceleration(acceleration);
    motor.move(distance);
    motor.run();
  }
}

Perhaps you need a mode==3 where it doesn't move.

Your code starts in mode==2 and thus moves downward repeatedly. It never changes to any other mode. If you only want to move 5000 steps once you should probably switch to mode==3 as soon as you initiate the downward move.

You don't seem to have any code to change the mode.

My guess is that you need to create a checkMode() function and call it from loop(). Then you will find that it doesn't get called while a motor is moving due to the WHILE loop in the moveup() and movedown() functions. That can be solved by moving the call to motor.run() into loop() and dispensing with the WHILEs in the functions.

...R

kyrollos:
I know how to make it move but I dont know how to make it stop. it just keeps going on and on, can someone help me make it stop?

Instead of telling the stepper to move by a given offset by move() , tell it to move to a specified position by moveTo(). Then it will stop itself.

Then it will stop itself.

Of course, the infinite loop won't end. But, at least the stepper will hold still.

Dealing with the infinite loops would be the first step. Then, deal with using the proper methods.

Thank you all so much, I changed it to moveTo() and it worked.
Thanks again.