How to control stepper motor position?

How to move the white thing until the end of the stepper motor?

I'm using this :

#include <AccelStepper.h>

#define DEG_PER_STEP 1.8
#define STEP_PER_REVOLUTION (360 / DEG_PER_STEP)

AccelStepper stepper(AccelStepper::FULL4WIRE, 7, 6, 5, 4);

long moveToPosition = STEP_PER_REVOLUTION;

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

  stepper.setAcceleration(200.0); // set acceleration
  stepper.setSpeed(200);          // set initial speed
  stepper.setCurrentPosition(0);  // set position to 0

  stepper.moveTo(STEP_PER_REVOLUTION); // move motor one revolution, in clockwise direction
  Serial.println("Motor moving in clockwise direction");
}

void loop() {
  if (stepper.distanceToGo() == 0) {
    Serial.println("Motor is stopped");
    delay(5000); // stop 5 seconds
    stepper.setCurrentPosition(0); // reset position to 0
    moveToPosition = -1 * moveToPosition; // reverse direction

    stepper.moveTo(moveToPosition); // move motor one revolution

    if (stepper.distanceToGo() > 0)
      Serial.println("Motor moving in clockwise direction");
    else if (stepper.distanceToGo() < 0)
      Serial.println("Motor moving in anticlockwise direction");
  }

  // Serial.print(F("position: "));
  // Serial.println(stepper.currentPosition());

  stepper.run(); // MUST be called as frequently as possible
}


It only moves a little bit.

You told it to move one revolution. That's one thread. Count the number of threads you want to move and multiply by that. I think it's probably somewhere over 200 threads so try:

stepper.moveTo(200ul * STEP_PER_REVOLUTION); // move motor one revolution, in clockwise direction

The 'ul' at the end of '200ul' tells the compiler that you want to do the math with an 'unsigned long' value so you can go over 32767 without overflow. 200 * 200 is 40000.

moveTo() is an absolute move so you should use stepper.moveTo(0); to go back to the start. If you move to negative numbers you will try to go past the beginning and jam against the motor.

Just to comment, a stepper doesn’t have an ‘end’.

It’s a continuous rotation device, so it’s important that you know where you’re starting from and where you’re going.

Limit switches or current sensing can help learn your limits or index points.