Setting CW / CCW Starting direction in Homing

Below is my homing code for the stepper motor. I am facing a strange problem. During homing, after power on, sometimes the stepper moves CW and sometimes CCW. This behavior causes further steps during homing to not function properly. Please review and let me know how I can set the starting direction so that Stepper always starts in the CW direction.

I tried to set direction using StepperZ.setDirection(1) but it gives compilation error.

As far as other steps are working fine. Based on initial conditions, void Home_Z is executed correctly. Please guide.

void Home_Z() {
  Serial.println("Home_Z");

  if (Paint_Home == 0) {
    while (digitalRead(limitSwitch_R) == 1) {
      stepperZ.setSpeed(5000);
      stepperZ.moveTo(-initial_homing);
      stepperZ.runSpeed();
      stepperZ.setCurrentPosition(0);  // Set this position as 0
      Serial.println("Running");
      break;
    }
  }

  if (digitalRead(limitSwitch_R) == 0) {
    // We hit the limit switch, so first stop and run to initial position
    stepperZ.stop();
    Serial.println("Stopped");
    delay(50);                       // Short delay for the stop to take effect
    stepperZ.setCurrentPosition(0);  // Set this position as 0

    delay(100);
    stepperZ.setSpeed(5000);
    stepperZ.move(Attach_Length_Steps);  // Move back Attach_Length_Steps from switch
    // Move back from the switch towards Left Limit_Switch
    while (stepperZ.currentPosition() != Attach_Length_Steps) {
      stepperZ.runToPosition();
      // In case Left Limit Switch is hit, break the loop
      if (digitalRead(limitSwitch_L) == LOW) {
        break;
      }
    }
    stepperZ.setCurrentPosition(0);
  }
  stepperZ.setCurrentPosition(0);  // Set this position as 0
  Serial.println(stepperZ.currentPosition());
  return;
}

For easy the help, post your project complete code and wiring schematic.

1 Like

assuming the home position is the most CCW position, the homing algorithm shouldn't hava a choice, it should always step in the CCW direction, one step at a time until the home switch becomes active.

if the position is zeroed when homing is complete, moving to the home position should always be to position zero

Try;

stepperZ.setSpeed(100);