button to stop stepper

Hi i am working on a project where i need to stop stepper at home, for this i decided to add a stop switch to stop stepper when it presses, i tried but my switch is not working , please help i am posting my code below

#include <AFMotor.h>
#include <Wire.h>
#define home_switch 50 

AF_Stepper motor(48, 1);



void setup() {

// Start Homing procedure of Stepper Motor at startup

while (!digitalRead(home_switch)) {  // Do this until the switch is activated   
motor.setSpeed(10);  // 10 rpm
Serial.println("Interleave coil steps");
       motor.step(2400, FORWARD, INTERLEAVE);
       delay( 2000) ; 
}

while (digitalRead(home_switch)) { // Do this until the switch is not activated
motor.release();

}

motor.step(0, FORWARD, INTERLEAVE);  // Reset position variable to zero
 
}

void loop() {

}

First, edit your post to include [ code ] tags around your code. The forum software eats some of your code if you don't.

Second, you never declared what kind of input you are using. It will default to a floating input. Do you have an external pullup or pulldown resistor?

Which Arduino are you using?

Thanks i have edited post :slight_smile:

I am using push button for input this is the button digram here and i am using Arduino MEGA

Look at the example program to see how to use a switch in your program.

Paul

By the reference from many examples i have written above code, please help or tell me where is the issue. my stepper is running but when i press button its not stopping the stepper.

My guess is that the line motor.step(2400, FORWARD, INTERLEAVE); will complete the full movement before it passes on to the the next line which is delay(2000); and which will also block the Arduino for a further 2 seconds before the button is tested.

You probably need to move the stepper one step at a time and check the switch between steps.

The AccelStepper library will probably be more suitable as it has non-blocking motor moves.

...R
Stepper Motor Basics
Simple Stepper Code

thanks for your help...yesterday i have done some R&D and written the very simple code to solve this problem :slight_smile:

abhixs:
thanks for your help...yesterday i have done some R&D and written the very simple code to solve this problem :slight_smile:

Good to hear.

It may help others if you explain what you did and post your working program.

...R

abhixs:
thanks for your help...yesterday i have done some R&D and written the very simple code to solve this problem :slight_smile:

Now that your code can find the switch, you may realize the stepper has actually moved a bit beyond where the switch was pressed.

Now add code to single step the motor back away from the switch until the switch turns off. Then your motor is at the proper stop point.

Paul