Basically I have created the following code to control my stepper motor:
int pin_enable_motor_x = 38;
int pin_motor_step_x = A0;
int pin_direction_x = A1;
int endstop_x = 3;
void setup() {
pinMode(pin_enable_motor_x, OUTPUT);
pinMode(pin_motor_step_x, OUTPUT);
pinMode(pin_direction_x, OUTPUT);
pinMode(endstop_x, INPUT);
digitalWrite(pin_enable_motor_x, LOW);
for (int i = 0; i < 200000; i++) {
runMotorSingleStepX(100, false); // runMotorSingleStepX(int delay, boolean direction)
if (digitalRead(endstop_x) == true) {
break;
}
}
}
void loop() {
}
void runMotorSingleStepX(int wait, boolean value) { //dir(pino),
digitalWrite(pin_direction_x, value);
digitalWrite(pin_motor_step_x, HIGH);
delayMicroseconds(wait);
digitalWrite(pin_motor_step_x, LOW);
delayMicroseconds(wait);
}
The idea is that the stepper motor will give many single steps until it reaches my mechanical endstop. But what really happens is that it detects true random pulses even when my endstop isn't pressed. So my motor stops before the point it should stop. I'm not sure if it's a common problem and I should be using some tricks to fix this problem.
Does anyone know what could be happening supposing that my electronics circuit is properly settled?