Problem with stepper motor behaviour

I'm trying to make a stepper motor run "x" number of rotations clockwise and "y" number of rotations counter clockwise.

This is the code I am using:

#define dirPin 2
#define stepPin 3
#define stepsPerRevolution 1600
int pd = 100;

void setup()

{
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {

  digitalWrite(dirPin, HIGH);
  for (int i = 0; i < 20 * stepsPerRevolution; i++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(pd);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(pd);
  }
  delay(1000);

  digitalWrite(dirPin, LOW);
  for (int i = 0; i < 20 * stepsPerRevolution; i++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(pd);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(pd);
  }
  delay(1000);
}

The line "20 * stepsPerRevolution" appears in the code two times, when the motor is rotating clockwise and when the motor is rotating counter clockwise. If both numbers are anything below 21, the motor behaves normally. But if the numbers are anything above 20, the motor doesn't spin at all.

And if one of the numbers is 20 and the other is anything above 20, the motor doesn't change directions, but spins 20 rotations in one direction, stops, and spins again 20 rotations in the same direction.

The motor I'm using is a 4.2A Nema23 motor, driver is DM556, connected to Arduino Mega.

Maybe someone has idea why this is happening, or can suggest some other code for me.

Thank you.

I believe your problem is here:

"int i"

the 'int' type will range from -32 768 to 32 767.

21*16 000 > 32 767 and will be interpreted as a negative number

try changing this to 'unsigned int' which ranges from 0 to 65 535.

hope that helps

20*1600 won't fit in an int type, use long int

EDIT: Nevermind, by using long and putting "L" after the number I got it to work. Thank you again for helping.

treplev:
Hi again, thanks for helping.

By using "unsigned int" (or "long") I managed to make the motor turn 163 revolutions in both directions. However, I would need it to run longer, at least two times as much. Is that possible?

Or, is it anyway possible to make a stepper motor run 5 minutes in one direction and 5 minutes the other direction?

Sorry if this is obvious, but I've tried googling this for the past couple of hours.

Thanks!

It sounds like you are interested in time rather than actual number of steps. In that case I would recommend you use the millis() call to determine whether 5 minutes have passed which would be 5601000 or 300,000 milliseconds.