stepper motor to home position at start


I am working on a project in which i need to set steeper motor home position at start, My code is working fine but i am facing a problem.

when my steeper motor not at home position then after powering Arduino its come to home and then loop starts,

But when my steeper motor at home position then after powering Arduino loop not starts

please suggest me whats the issue, my code is given below:

#include <AFMotor.h>
#include <Wire.h>
//#define home_switch 50 // Pin 9 connected to Home Switch (MicroSwitch)

AF_Stepper motor(48, 1);

int LimitSwitch = 46;

void setup() {

// Start Homing procedure of Stepper Motor at startup

 //switch setup*********************************
pinMode(LimitSwitch, INPUT_PULLUP);

//Send myMotor to it's HOME position when waiting for input
  while (digitalRead(LimitSwitch) == HIGH)
    motor.setSpeed(10);  // 10 rpm
    motor.step(2400, FORWARD, INTERLEAVE);
  while (digitalRead(LimitSwitch) == LOW)
 motor.setSpeed(10);  // 10 rpm
    motor.step(1, FORWARD, INTERLEAVE);


void loop() {


That code seems to tell the motor to move 2400 steps if the limit switch is not pressed. What happens if the switch gets pressed after (say) 117 steps?

If it was my program I would move one step between each test of the limit switch.

And what is the purpose of the second WHILE - it seems to keep the motor going in the same direction even after the switch is pressed.

Stepper Motor Basics
Simple Stepper Code