Help With AccelStepper Code

#include <AccelStepper.h>

#define dirPin 2
#define stepPin 3
#define motorInterfaceType 1
#define stepsPerRev 1600 // defined via driver

int rotations;
int target;

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);


void setup() {
  // put your setup code here, to run once:

  // Start serial communication:
  Serial.begin(9600);

  // Set max speed and acceleration/deceleration:
  stepper.setMaxSpeed(3200); // steps/sec
  stepper.setAcceleration(3200); // steps/sec^2

}

void loop() {
  // put your main code here, to run repeatedly:

  // Display rotations message:
  Serial.println("How many rotations would you like to turn?");
  while (Serial.available()==0) {
    // exits loop once input is made
  }

  // read rotations message:
  rotations=Serial.parseInt();
  Serial.print("The motor will turn: ");
  Serial.print(rotations);
  Serial.println(" rotations");

  delay(1000); // wait 1 sec

  // move to target
  target = stepsPerRev * rotations;
  stepper.moveTo(target);
  stepper.runToPosition();
  

  exit(0); // exits the loop

}

This code is for turning a stepper motor. The code asks the user how many revolutions the motor will spin. The problem with this code is that every time I enter a value greater than 20, the motor spins the opposite direction (counter clockwise) and only spins 20 revolutions (no matter if I enter 25 for example). Why is this?

You're seeing integer overflow.

Make target and stepsPdrRev long rather than int.

1 Like

That fixed it, thank you! I am new to this stuff.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.