How to avoid stepper motor to revert its spin direction

0

I'm working with an Arduino UNO and a stepper motor NEMA 17. I would like to know how to avoid the stepper motor to revert its spin direction when I apply a load in the shaft. The motor works as I spect without any load, here is the code I'm using.

I think I'm missing something in the code, not in the connections.

// Define pin connections & motor's steps per revolution
const int dirPin = 2;
const int stepPin = 3;
const int stepsPerRevolution = 45;//115

void setup()
{
  // Declare pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}
void loop()
{
  
if(true){
    // Set motor direction counterclockwise
  digitalWrite(dirPin, HIGH);

  // Spin motor quickly
  for(int x = 0; x < stepsPerRevolution; x++)
  {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(700); //670
    digitalWrite(stepPin, LOW);
    delayMicroseconds(700); //670
  }
  
  }
}

External voltage: 12 v 3A max

Motor's datasheet: 17HS4401S

Driver: DRV8825

Sketch

Do you mean that the motor is too weak to hold the load?

Have you set the current limit on the driver?

Does it happen at slower speeds?

That is, make the delay longer (1000 - 5000)?

Why is the code so complicated ?

There is no need for the if (true) test or the digitalWrite(dirPin, HIGH); in loop(), nor any need for the for loop because loop() does what its name suggests

Ground fungus is also correct. Is the coil current set correctly?

Also - stepper motors have a "holding torque" rating. This is the extent to which they resist a load from moving the shaft.
But it means keeping the stepper powered in that holding position. If you de-energise the coils the motor will spin freely.
If the coils are energises and still moves, you need a bigger stepper. Alternatively, you can use an magnetic brake on the shaft.
Note that leaving a stepper with coil powered is acceptable but it will often get quite hot. Often extremely hot - burn level hot even.