stepper motor automatically changes the direction of rotation

I try to drive my nema17 with a Tb6560 and arduino UNO card.
the motor start perfectly the problem begins when I try to block the motor with my hand the motor changes automatically and quickly the direction of rotation.

what can be the cause please?

#include “AccelStepper.h”

float rpm = 2000;
int microStep = 1;
int stepsPerRev = 200;
int enablePin = 2;
float maxSpeed = (rpm / 60) * microStep * 200;
long timeSinceLastReadout = 0L;

AccelStepper stepper(AccelStepper::DRIVER, 10, 9); //driver mode,step pin,dir pin

void setup()
{
pinMode(enablePin, OUTPUT); // set pin to input
digitalWrite(enablePin, HIGH); // turn on pullup resistors
stepper.setMaxSpeed(1000);//maxSpeed);
stepper.setAcceleration(500);
stepper.moveTo(1024000); // don’t need to target any further than this
}

void loop()
{
int speed = stepper.speed();
if ((int)stepper.speed() < (int)maxSpeed)
{
digitalWrite(enablePin, LOW);
stepper.run();
}
else {
digitalWrite(enablePin, LOW);
stepper.runSpeed();
}
}

It may help to change this

stepper.moveTo(1024000); // don't need to target any further than this

to

stepper.moveTo(1024000UL); // don't need to target any further than this

Remember that the code will continue to step even if you hold the motor stationary. The speed is determined by the rate at which steps are produced, not by the actual speed of the motor.

...R

unfortunately it did not work I still have the same problem, as soon as I put my hand on the rod to test the torque the stepper changes the direction of rotation without any resistance

achakar:
unfortunately it did not work I still have the same problem, as soon as I put my hand on the rod to test the torque the stepper changes the direction of rotation without any resistance

Do you mean that the system is affected just by gently touching a finger to the motor shaft?

If so that suggests a bad electrical connection somewhere - perhaps a missing GND connection.

Make a simple pencil drawing showing how everything is connected and post a photo of the drawing. See this Simple Image Guide

...R

The current limit is set correctly on the driver? What motor are we talking about?
The power supply is a sensible voltage?