Stopping a stepper motor when it reaches an endstop

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?

Hi,
Welcome to the forum.

How have you got your endstop wired, if it pulls the input to 5V when ON, have you got a 10K resistor from the input to gnd, to pull the input down when the switch is open?

Also int i will never get to 200000, check the range of int variable. (Read the error listing below your code window.)

Tom... :slight_smile:

If you use pinMode(pin, INPUT_PULLUP); you can take advantage of the internal pullup resistor. But your switch needs to pull the line to GND and digitalRead() will give LOW when the switch is pressed.

...R

Thanks, I changed my INPUT to INPUT_PULLUP and also added one 10K resistor and it solved the problem...

Just changing the INPUT to INPUT_PULLUP made the endstop detection more stable but it still was stopping before the right time sometimes. The 10K resistor solved completely the problem.

and also added one 10K resistor

Added it where? Without knowing how you used the resistor, your claim that the switch is more stable now is just blowing smoke.