for(int i =4000 ; i>0 ;i--)
{
val=digitalRead(SWITCH);
if(val == HIGH) //switch is closed
{
digitalWrite(4,HIGH);
digitalWrite(LED, HIGH);
}
}
How long do you think it will take to race through this block of code? Will the stepper motor have caused the switch to be closed by then?
//while(Stepper1.currentPosition() !=Stepper1.targetPosition())
Uncomment this. Get rid of the for loop and the opening and closing brace, but not the code inside the braces.
Add a break statement to the if block, so the while loop is terminated.
You will also need tell the Stepper1 instance to go to the current position, so it stops trying to get to the target position. That is, the new target position is the current position.