Interrupt function misbehaving when powering up stepper driver

Hi,
I'm new to this and has run into a problem with the interrupt function that I cannot figure out. I have 2 limit switches to stop the stepper at the end of travel, one for HOMING and the other for MAX travel. The interrupt function (FALLING) seems to work fine when I test the limits by manually pressing and releasing it.

The problem comes when I power up the stepper driver; the interrupt function still stops the motor when it makes (closes) the limit but when I send a command to move away from the limit (limit open) then it appears as if it sees a FALLING interrupt pin and stop the stepper as soon as the contact open on the limit switch.
I have tried everything, debouncing, changing limit switches and RC circuits but the problem persists.

Could you please look at the code and tell me if there is something obvious wrong.

#include <math.h>
#include <AccelStepper.h>

//User-defined values
long receivedSteps = 0; //Number of steps
long receivedSpeed = 0; //Steps / second
long receivedAcceleration = 0; //Steps / second^2
char receivedCommand;   // character, speed, steps etc.
long receivedMMdistance = 0; //distance in mm from the Serial Monitor
long receivedDelay = 0; //delay between two steps, received from the Serial Monitor
long receivedDistance = 0;   // user desired distance (mm)
long receivedPosition = 0;   // user defined position on axis (mm)
const double screwPitch = 1.5;   //  Drive screw pitch (mm)- change to 1500micron for better accuracy
const int stepPerRev = 400;
const int defaultMaxSpeed = 400;    // set maximum speed for HOMING purposes - steps/s


//-------------------------------------------------------------------------------

int directionMultiplier = 1; // = 1: positive direction, = -1: negative direction
bool newData, runallowed = false; // booleans for new data from serial, and runallowed flag
const byte ledPin = 13;   // led status pin, visual feedback from limit switch activation
const byte interruptPin_1 = 2;    // pin for the homing microswitch using attachInterrupt(); - travel away from switch (POS)
const byte interruptPin_2 = 3;    // pin for the end stop microswitch using attachInterrupt(); - travel away from switch (NEG)

// Test to see if I can get a better debounce response
long debouncing_time = 15; //Debouncing Time in Milliseconds
volatile unsigned long last_micros;

AccelStepper stepper(1, 8, 9);// direction Digital 9 (CCW), pulses Digital 8 (CLK)

void setup()
{
  Serial.begin(9600); //define baud rate
  Serial.println(" - Demonstration of a 1-D axis using the AccelStepper Library and attacheInterrupt() - \n"); //print a message
  Serial.println("Default speed: 400 steps/s, default acceleration: 1000 steps/s^2. \n");
  Serial.println("Send 'C' for printing the commands. \n");

  pinMode(interruptPin_1, INPUT_PULLUP); /* internal pullup resistor (debouncing); if you choose FALLING, make sure that the switch
    connects the pin 2 to the GND when it is pressed. */

  attachInterrupt(digitalPinToInterrupt(interruptPin_1), debounceInterrupt, FALLING); /* /You can change FALLING but make sure that you connect
    the switch to GND or +5V accordingly! */

  pinMode(interruptPin_2, INPUT_PULLUP); /* internal pullup resistor (debouncing); if you choose FALLING, make sure that the switch
    connects the pin 3 to the GND when it is pressed. */

  attachInterrupt(digitalPinToInterrupt(interruptPin_2), debounceInterrupt, FALLING); /* /You can change FALLING but make sure that you connect
    the switch to GND or +5V accordingly! */

  //LED pins, OFF by default
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);


  //setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2500); // SPEED = Steps / second
  stepper.setAcceleration(1000); // ACCELERATION = Steps /(second)^2


  stepper.disableOutputs(); //disable outputs; so the motor does not get warm (no current)
}

//  ------------------------------- Main LOOP ----------------------------------------------------------------

void loop()
{
  //Constantly looping through these 2 functions.
  //We only use non-blocking commands, so something else (should also be non-blocking) can be done during the movement of the motor

  checkSerial(); //check serial port for new commands
  RunTheMotor(); //function to handle the motor

}

//  ------------------------------- Run Motor --------------------------------------------------------------------

void RunTheMotor() //function for the motor
{
  if (runallowed == true)
  {
    // if (abs(stepper.currentPosition()) < receivedSteps) //abs() is needed because of the '<'
    // if (stepper.currentPosition() != receivedSteps)    // confirm new position is not on current position

    stepper.enableOutputs(); //enable pins
    stepper.run(); //step the motor (this will step the motor by 1 step at each loop)

  }

  else // program enters this part if the runallowed is FALSE i.e HOME or Distance travelled, don't do anything
  {
    runallowed = false;   //disable running -> the program will not try to enter this if-else anymore
    stepper.disableOutputs(); //disable outputs

  }
}

//  ----------------------------------- Check Serial - Receive Commands  ------------------------------------------

void checkSerial() //function for receiving the commands
{
  if (Serial.available() > 0) //if something comes from the computer
  {
    receivedCommand = Serial.read(); // pass the value to the receivedCommad variable
    newData = true; //indicate that there is a new data by setting this bool to true

    if (newData == true) //we only enter this long switch-case statement if there is a new command from the computer
    {
      switch (receivedCommand) //we check what is the command
      {

        case 'P': /* P uses the move() function of the AccelStepper library, which means that it moves relatively to the current position.
                      Movement is in the POSITIVE direction */

          if (digitalRead(interruptPin_2) != LOW )    /* && runallowed == false)    // check if end stop limit switch is not activated */
          {
            receivedDistance = Serial.parseFloat(); //value for the steps
            receivedSpeed = Serial.parseFloat(); //value for the speed
            directionMultiplier = 1; //We define the direction
            Serial.println("Positive Direction Movement: \n"); //print the action
            RotateRelative(); //Run the function

            //example: P2000 400 - 2000 steps (5 revolution with 400 step/rev microstepping) and 400 steps/s speed
            //In theory, this movement should take 5 seconds
          }

          else
          {
            Serial.println("\n Limit Switch Activated! - Unable to move in POSITIVE direction \n");  // Inform user that tbe limit switch has been activated
          }
          break;

        case 'N': /*  N uses the move() function of the AccelStepper library, which means that it moves relatively to the current position.
                      Movement is in the NEGATIVE direction */

          if (digitalRead(interruptPin_1) != LOW) // && runallowed == false)    // check if end stop limit switch is not activated
          {
            receivedDistance = Serial.parseFloat(); //value for the steps
            receivedSpeed = Serial.parseFloat(); //value for the speed
            directionMultiplier = -1; //We define the direction
            Serial.println("\n Negative Direction Movement: \n"); //print action
            RotateRelative(); //Run the function

            //example: N2000 400 - 2000 steps (5 revolution with 400 step/rev microstepping) and 500 steps/s speed; will rotate in the other direction
            //In theory, this movement should take 5 seconds
          }

          else
          {
            Serial.println("\n Limit Switch Activated! - Unable to move in NEGATIVE direction \n");  // Inform user that tbe limit switch has been activated
          }
          break;


        case 'R': //R uses the moveTo() function of the AccelStepper library, which means that it moves absolute to the current HOME position.

          if (digitalRead(interruptPin_2) != LOW )    // check if end stop limit switch is not activated
          {
            receivedPosition = Serial.parseFloat(); //value for the steps
            receivedSpeed = Serial.parseFloat(); //value for the speed
            directionMultiplier = 1; //We define the direction
            Serial.println("Absolute position (+)."); //print the action
            RotateAbsolute(); //Run the function

            //example: R800 400 - It moves to the position which is located at +800 steps away from 0.
          }

          else
          {
            Serial.println("\n Limit Switch Activated! - Unable to move to specified ABSOLUTE position \n");  // Inform user that tbe limit switch has been activated
          }

          break;

        case 'r': //r uses the moveTo() function of the AccelStepper library, which means that it moves absolute to the current HOME position.

          if (digitalRead(interruptPin_1) != LOW) //    check if end stop limit switch is not activated
          {
            receivedPosition = Serial.parseFloat(); //value for the steps
            receivedSpeed = Serial.parseFloat(); //value for the speed
            directionMultiplier = -1; //We define the direction
            Serial.println("Absolute position (-)."); //print the action
            RotateAbsolute(); //Run the function

            //example: r800 400 - It moves to the position which is located at -800 steps away from 0.

          }

          else
          {
            Serial.println("\n Limit Switch Activated! - Unable to move to the specified ABSOLUTE position \n");  // Inform user that tbe limit switch has been activated
          }

          break;

        case 'S': // Stops the motor

          stepper.stop(); //stop motor
          stepper.disableOutputs(); //disable power
          Serial.println("Stop command received! \n"); //print action
          runallowed = false; //disable running
          break;

        case 's': // Stops the motor

          stepper.stop(); //stop motor
          stepper.disableOutputs(); //disable power
          Serial.println("Stop command received! \n"); //print action
          runallowed = false; //disable running
          break;

        case 'A': // Updates acceleration

          runallowed = false; //we still keep running disabled, since we just update a variable
          stepper.disableOutputs(); //disable power
          receivedAcceleration = Serial.parseFloat(); //receive the acceleration from serial
          stepper.setAcceleration(receivedAcceleration); //update the value of the variable
          Serial.print("New acceleration value: "); //confirm update by message
          Serial.println(receivedAcceleration); //confirm update by message
          break;

        case 'L': //L: Location

          runallowed = false; //we still keep running disabled
          stepper.disableOutputs(); //disable power
          Serial.print("Current location of the motor: ");//Print the message
          Serial.println(stepper.currentPosition()); //Printing the current position in steps.
          break;

        case 'H':  //H: Re-establish the HOME position

          runallowed = true;
          Serial.println("HOMING"); //Print the message
          Homing();// Run the HOMING function
          break;

        case 'h': //h: Go to HOME position (could be different from H: Homing, if changed by USER

          runallowed = true;
          Serial.println("Go Home"); //Print the message
          GoHome();// Run the function
          break;

        case 'U':   // New home position

          runallowed = false; //we still keep running disabled
          stepper.disableOutputs(); //disable power
          stepper.setCurrentPosition(0); //Reset current position. "new home"
          Serial.print("The current position is updated to: "); //Print message
          Serial.println(stepper.currentPosition()); //Check position after reset.
          break;

        case 'I':    // Check Status of the interrupt pins

          Serial.print("Interrupt Pin 1 Status: ");
          Serial.println(digitalRead(interruptPin_1));
          Serial.print("Interrupt Pin 2 Status: ");
          Serial.println(digitalRead(interruptPin_2));
          break;

        case 'C':

          PrintCommands(); //Print the commands for controlling the motor
          break;

        default:

          break;
      }
    }

    newData = false;       //after we went through the above tasks, newData is set to false again, so we are ready to receive new commands again.
  }
}

//  -------------------------------------HOME on Limit Switch --------------------------------------------------

void Homing()   // HOME the motor on a limit switch
{
  stepper.setMaxSpeed(400); //set speed manually to 400. In this project 400 is 400 step/sec = 1 rev/sec.
  directionMultiplier = -1; //We define the direction - NEGATIVE towards limit switch #1

  // noInterrupts();

  if (stepper.currentPosition() == 0 && digitalRead(interruptPin_1) == LOW)   // check current position before moving
  {
    Serial.println("Currently at the HOME position.");    // inform user that carrage is at the HOME position

  }

  else
  {
    do    // run motor continious until it reached a limit switch

    {
      stepper.enableOutputs(); //enable pins
      stepper.setSpeed(-400);   // set the interval speed for homing (pulses/s)
      stepper.runSpeed();   // run the motor, no acceleration

    }     while (digitalRead(interruptPin_1) == HIGH);

    stepper.setCurrentPosition(0); //Reset current position - "default HOME position"
    Serial.print("At HOME position: ");   // confirm the current position
    Serial.println(stepper.currentPosition());
    Serial.println();
    runallowed = false;
    stepper.disableOutputs(); //disable power
  }
}

//  ----------------- Go to USER Defined HOME ----------------------------------------------------

void GoHome()   // Move to a user defined HOME position, could be the DEFAULT HOME position if no USER HOME position has been set
{
  stepper.setMaxSpeed(400); //set speed manually to 400. In this project 400 is 400 step/sec = 1 rev/sec.

  if (stepper.currentPosition() == 0)
  {
    Serial.println("Currently at the USER HOME position.");
    runallowed = false;
    stepper.disableOutputs(); //disable power
  }
  else
  {
    stepper.enableOutputs(); //enable pins
    stepper.setSpeed(400);
    stepper.moveTo(0); //set abolute distance to move
  }
}

//    ------------------------------ Relative MOvement -----------------------------------------

void RotateRelative()
{
  //We move X steps from the current position of the stepper motor in a given direction.
  //The direction is determined by the multiplier (+1 or -1)

  runallowed = true; //allow running - this allows entering the RunTheMotor() function.
  receivedSteps = directionMultiplier * ((stepPerRev * receivedDistance) / screwPitch);    // Calculate number of steps to complete the distance
  stepper.setMaxSpeed(receivedSpeed); //set speed (pulses / sec)
  stepper.move(receivedSteps); // set relative distance and direction
}

//    ------------------------------ Absalute MOvement -----------------------------------------

void RotateAbsolute()
{
  //We move to an absolute position - relative to HOME location.
  //The AccelStepper library keeps track of the position.
  //The direction is determined by the multiplier (+1 or -1)
  //Why do we need negative numbers? - If you drive a threaded rod and the zero position is in the middle of the rod...

  runallowed = true; //allow running - this allows entering the RunTheMotor() function.

  if (receivedPosition == stepper.currentPosition())
  {
    Serial.println("Required position is the same as current position! \n");

  }
  else
  {
    receivedSteps = ((stepPerRev * receivedPosition) / screwPitch);    // Calculate number of steps to complete the distance
    stepper.setMaxSpeed(receivedSpeed); //set speed (pulses / sec)
    stepper.moveTo(directionMultiplier * receivedSteps); //set relative distance
  }

}

//  --------------------------- Interrupt Debouncing -----------------------------------------

// Test to improve debouncing limit switches
void debounceInterrupt() {

  Serial.print("interruptPin_1 Status (bebounce): ");   // Output for debugging
  Serial.println(digitalRead(interruptPin_1));
  Serial.print("interruptPin_2 Status (bebounce): ");   // Output for debugging
  Serial.println(digitalRead(interruptPin_2));
  Serial.println("");

  if ((long)(micros() - last_micros) >= debouncing_time * 1000)
  {
    stopMotor();
    last_micros = micros();
    
  }
}

//  -------------------------- STOP MOTOR ------------------------------------------------------

void stopMotor()//function activated by the pressed microswitch or E-stop command
{
  //Stop motor, disable outputs; here we should also reset the numbers if there are any

  Serial.print("interruptPin_1 Status (Stop Motor): ");   // use for debugging
  Serial.println(digitalRead(interruptPin_1));            // use for debugging
  Serial.print("interruptPin_2 Status (Stop Motor): ");   // use for debugging
  Serial.println(digitalRead(interruptPin_2));            // use for debugging

  if (digitalRead(interruptPin_1) == 0)
  {
    runallowed = false; //  disable running
    stepper.stop(); //stop motor
    Serial.println("MOTOR STOPPED! \n"); // print action
    stepper.disableOutputs(); //disable power


  }

  else if (digitalRead(interruptPin_2) == 0)
  {
    runallowed = false; //  disable running
    stepper.stop(); //stop motor
    Serial.println("MOTOR STOPPED! \n"); // print action
    stepper.disableOutputs(); //disable power

  }

  else
  {
    /*Serial.print("interruptPin_1 Status (Stop Motor else:) ");  // output for debugging
      Serial.println(digitalRead(interruptPin_1));
      Serial.print("interruptPin_2 Status: ");
      Serial.println(digitalRead(interruptPin_2)); */
  }

}

//  ------------------------------- Print Commands  --------------------------------------------
void PrintCommands()
{
  //Printing the commands
  Serial.println(" 'C' : Prints all the commands and their functions.");
  Serial.println(" 'P' : Rotates the motor in positive (CW) direction, relative.");
  Serial.println(" 'N' : Rotates the motor in negative (CCW) direction, relative.");
  Serial.println(" 'R' : Rotates the motor to an absolute positive position (+).");
  Serial.println(" 'r' : Rotates the motor to an absolute negative position (-).");
  Serial.println(" 'S' : Stops the motor immediately.");
  Serial.println(" 's' : Stops the motor immediately.");
  Serial.println(" 'A' : Sets an acceleration value.");
  Serial.println(" 'L' : Prints the current position/location of the motor.");
  Serial.println(" 'H' : Goes back to 0 position from the current position (homing).");
  Serial.println(" 'U' : Updates the position current position and makes it as the new 0 position. ");
  Serial.println(" 'I' : Check the status of the interrupt pins. ");
}

Please read the forum guidelines to see how to properly post code and some information on making a good post.

Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

Please go back and fix your original post.

My bad, thanks. Its correctly formatted now

shouldn't you only monitor the limit switch when moving towards it?

why call noInterrupt () inside an interrupt?

I forgot to delete it, it was something I tried to see if I can get it to work

How are you powering the stepper motor? It could be a power issue.

I'm not sure why you would want to use interrupts in this application. It is VERY difficult to debug your code because you are reading interruptPin_1 and interruptPin_2 from loop() and also in the ISR. Given that an interrupt can occur ANYWHERE in the code it is going to be difficult to account for every situation where the interrupt can occur.

In any case, you have violated several "no-no's" when using interrupts:

  • All variables shared between ISR and non-ISR code should be declared with the volatile keyword.
  • You should not call any function which performs I/O that depends on interrupts in an ISR.
  • Interrupts should be as short as possible. Usually increment a counter, set a flag, read/write a register/buffer.
  • Using interrupts when you don't absolutely need to makes the code difficult to debug and manage.

Also, not all functions in libraries are safe to call at interrupt level (i.e., in an ISR). Not sure about accelstepper functions but I avoid calling library functions in ISRs unless I know for sure they are safe to call. Indeed, I find it rare I need to use interrupts at all because even when they are necessary it is usually handled by a library associated with a particular device I am using.

I'm powering the stepper with a DM542A stepper driver. The driver is powered by an LRS-350-36 power supply.

The interrupts are there to stop the stepper when the limit is made, I could have both wired up and monitored with one interrupt, but I trying to simulate 2 different axis's. I've built one axis which I'm using to test and experiment. The plan is to add a jogging switch (rotary encoder) when I manages to get the limit issues resolved.

The coding seem to work fine if the stepper driver/stepper is not powered up; I tested and checked it with outputs to the Serial monitor but as soon as the stepper driver is powered up then I get the undesired responses that looks like bouncing switches.

I'm not sure what you mean that I read the interrupts in the loop(), I only monitor the Serial Monitor and run the stepper in the loop. The ISR is used to stop the stepper immediately as soon as a limit is made.

I'm new to this and am sure I will have many no-no's in my code and appreciate it been pointed out to me.

i'm not familiar with the AccelStepper library.

rather that invoke some function to individually step the motor, it looks like its moveTo() will step the motor the specified # of steps.

if the code executed individual steps, it could abort when it detects that the limit switch closed.

i notice that your interrupt invokes stepper.stop(), presumably before moveTo() has completed.

is this valid?

The moveTo() move to a specific location relative to the Home (0) position.

Let me check on your comment about invoking the stop() before run command is complete. I don't use the moveTo() function when moving away from the limit but rather stepper.run() function.

but that was the command that was interrupted by the stop()

Hi gcjr,
You are right, I've tested it at it. the run() gets interrupted when I move away from the limit.

Now for the challenge to rewrite my code to make it work the way it should. I have changed it, the ISR now raise a flag that the interrupt was triggered, and I've added an if statement in the loop() to stop the stepper. It works but the stepper stops momentarily when moving away from the limit but complete the full number of steps.

I will work on it some more until I get it right.

Thanks so far for your help!

I said you are reading interruptPin_1 and interruptPin_2 from loop(), which is true and you are also reading them from the ISR. Do you understand how interrupts work? An interrupts can occur AT ANY TIME. One line of C++ code can translate to multiple machine instructions. Therefore, in some cases an interrupt can occur while executing a single line of C++ code! That is why I am concerned about calling library functions when it is very possible an interrupt can occur during a library function and during the interrupt another library function may be called! Unless all of the library functions are written to be re-entrant you will likely have an issue.

By the way, runallowed is not declared with the volatile keyword.

why not individually step the motor (1 step at a time) checking the limit switch each step and stop when the limit switch closes?

I did consider using polling to monitor the limit switches but decided to go with the interrupt function after seeing some comments that polling does slow your program down.

I have now solved the problem; I've simplified the ISR code to only raise an interrupt flag which is then used by the stopMotor code stop the motor.

With regards to homing, I have solved that by moving off the limit with a do-while loop until the limit just open and reset my ZERO at that position.

See sections below:

void loop()
{
  //Constantly looping through these 2 functions.
  //We only use non-blocking commands, so something else (should also be non-blocking) can be done during the movement of the motor

  checkSerial(); //check serial port for new commands
  
  if (interruptFlag == true)
    {
    stopMotor();  // stop motor function
    }
   
   else
   {
    
    RunTheMotor(); //function to handle the motor       
   }
}

 //  -------------------------------------HOME on Limit Switch --------------------------------------------------

void Homing()   // HOME the motor on a limit switch
{
  stepperX.setAcceleration(maxAcceleration);
  directionMultiplier = -1; // We define the direction - NEGATIVE towards limit switch #1

  if (stepperX.currentPosition() == 0 && digitalRead(interruptPin_1) == HIGH)   // check current position before moving
  {
    Serial.println("Currently at the HOME position.");    // inform user that carrage is at the HOME position

  }

  else
  {
    do    // run motor  continiously CW until it reached a limit switch

    {
      stepperX.setMaxSpeed( 1250 );      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.enableOutputs(); //enable pins
      stepperX.setSpeed( directionMultiplier * 1000 );   // set the interval speed for homing (pulses/s)
      stepperX.runSpeed();   // run the motor, no acceleration
      
    }     while (digitalRead(interruptPin_1) == HIGH);
  }
  
  delay(100);
  stepperX.setAcceleration( 1500 );  // Set Acceleration of Stepper
  directionMultiplier = 1;
  stepperX.setCurrentPosition(0); //Reset current position - "temp HOME position"
  
  if (stepperX.currentPosition() == 0 && digitalRead(interruptPin_1) == LOW)   // check current position before moving
  {
    do
      {        
        stepperX.setMaxSpeed( 1000 );      // Set Max Speed of Stepper (Slower to get better accuracy)
        stepperX.setSpeed( directionMultiplier * 600 );   // set the interval speed for homing (pulses/s)
        stepperX.runSpeed();   // run the motor, no acceleration         
      
      }   while (digitalRead(interruptPin_1) == LOW  /*== CHANGE*/); // Make the Stepper move CCW until the switch is deactivated
  }
    
    stepperX.setCurrentPosition(0); //Reset current position - "default HOME position"
    Serial.print("At HOME position: ");   // confirm the current position
    Serial.println(stepperX.currentPosition());
    Serial.println();
    stepperX.setAcceleration( maxAcceleration ); 
    runallowed = false;
    stepperX.disableOutputs(); //disable power
  
}

// Test to improve debouncing limit switches
void DebounceInterrupt()
{

  if ((long)(micros() - last_micros) >= debouncing_time * 1000 )
  {
      interruptFlag = true;  // set flag to true
      last_micros = micros();
    
  }
      previousFlip1 = digitalRead(interruptPin_1);
      previousFlip2 = digitalRead(interruptPin_2);
}
 
//  -------------------------- STOP MOTOR ------------------------------------------------------

void stopMotor()//function activated by the pressed microswitch or E-stop command
{
  //Stop motor, disable outputs; here we should also reset the numbers if there are any

    delay(15);

if (interruptFlag == true)
{
 
 if (previousFlip1 == 0 )
  {
      runallowed = false; //  disable running
      stepperX.stop(); //stop motor
      Serial.println("MOTOR STOPPED (interruptPin_1)! \n"); // print action
      
      Serial.print("interruptPin_1 Status (Stop Motor): ");   // use for debugging
      Serial.println(digitalRead(interruptPin_1));            // use for debugging
               
      stepperX.disableOutputs(); //disable power
  }
  
  else if (previousFlip2 == 0 )
  {
    runallowed = false; //  disable running
    stepperX.stop(); //stop motor
    Serial.println("Max Travel Limit Reached - (interruptPin_2)! \n"); // print action

    delay(100);
    stepperX.setAcceleration( 1500 );  // Set Acceleration of Stepper
    directionMultiplier = -1;  
    maxTravel = stepperX.currentPosition(); 
  
  if (digitalRead(interruptPin_2) == LOW)   // check if Limit Switch 2 is activated before moving off limit
  {
    do
      {        
        stepperX.setMaxSpeed( 1000 );      // Set Max Speed of Stepper (Slower to get better accuracy)
        stepperX.setSpeed( directionMultiplier * 600 );   // set the interval speed for homing (pulses/s)
        stepperX.runSpeed();   // run the motor, no acceleration         
      
      }   while (digitalRead(interruptPin_2) == LOW  /*== CHANGE*/); // Move CW until the switch is deactivated
  }
    
    // stepperX.setCurrentPosition(0); //Reset current position - "default HOME position"
    Serial.print("Max Travel Distance - (interruptPin_2)! ");   // confirm the maximum travel
    Serial.print((screwPitch * maxTravel) / (stepperXRev));
    Serial.println("mm \n");
    stepperX.setAcceleration( maxAcceleration ); 
    runallowed = false;
    stepperX.disableOutputs(); //disable power        
       
  }

  else
  {
    
  }  
      interruptFlag = false;  // set flag to back to false

}
}

//    ---------------- Interrupt ISR (Rotary Encoder) -------------------------------------
void JoggingSwitch()
{
  delay(20);  // delay for Debouncing
  
  if (digitalRead(encoderPinA) == LOW)
    {
    rotationDirection = digitalRead(encoderPinA);
    Serial.print("rotationDirection (A): ");
    Serial.println(rotationDirection);
    Serial.println();
    }
    // else
  else if (digitalRead(encoderPinB))
    {
    // rotationDirection = !digitalRead(encoderPinA);
    rotationDirection = digitalRead(encoderPinB);
    Serial.print("rotationDirection (B): ");
    Serial.println(rotationDirection);
    Serial.println();
    }
  
  TurnDetected = true;
}  

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.