How to stop Steper motor with interrupt.

Hi Guys.

I try to use a steeper motor from old scanner using this code:

/*
* Stepper_bipolar sketch
*
* stepper is controlled from the serial port.
* a numeric value followed by '+' or '-' steps the motor
*
*
* http://www.arduino.cc/en/Reference/Stepper
*/
#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 24
// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2, 3, 4, 5);
volatile int steps = 0;
void setup()
{
// set the speed of the motor to 30 RPM
stepper.setSpeed(300);
Serial.begin(9600);

}

void loop()
{
attachInterrupt(4, stop, FALLING);
if ( Serial.available()) {
char ch = Serial.read();
if(isDigit(ch)){ // is ch a number?
steps = steps * 10 + ch - '0'; // yes, accumulate the value
}
else if(ch == '+'){
stepper.step(steps);
steps = 0;
}
else if(ch == '-'){
stepper.step(steps * -1);
steps = 0;
}
}
}

void stop()
{
stepper.setSpeed(0);  //something here is wrong 

}

My problem: I want to control a stepper motor with numbers send to Arduino by serial. The space where scanner head can move is limited. When scanner head is near to limit, it hits the button and in this moment motor should be stopped. So it work like this for now, but when the interrupt made by button occurs sending numbers by serial don’t work and I need to restart Leonardo. How to go back to the main loop after interrupt. Or maybe there is a better way to turn off a motor without using interrupts?

Firstly don't call attachInterrupt() in loop(), call it as the last thing in setup().

If you look at the source for the Stepper library you'll see that 0 is not a valid value for setSpeed(), since it divides by zero if you do that.

Secondly there is no way to stop the library once step() has been called. You might have more luck either stepping a single step at a time and managing the speed yourself, or better move over to the AccelStepper library.

Thanks for You reply, I'll do more research.