AttachInterrupt() and Step() function

I have a problem with my code. My stepper motor did not update the rotation as IR sensor sense obstacle WHILE IT STILL ROTATING. Problem here, the motor will finish rotate first then it will read next value. This is for escltor project. HELP ME :frowning:

#include <Stepper.h>


#define STEPS_PER_MOTOR_REVOLUTION 32   
const byte interruptPin = 2; //IR sensor

Stepper stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

float steps2take=STEPS_PER_MOTOR_REVOLUTION*32; //adjust to take how much it rotates

void setup()   {
  
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), receiveIR, LOW);

}

void loop()   
{


}
void receiveIR
{
int value=digitalRead(IR);
if(value==LOW)
  {
  
  stepper.setSpeed(500);   //speed
  stepper.step(steps2take);//steps to take
  
  }
  else
  {
  stepper.step(0); //steps to take
  }
}

Problem here, the motor will finish rotate first then it will read next value.

Yes it will, this is because you are using a library that has blocking code. That is it does not return until the motor reaches the set position. Therefore the code is still in the interrupt routine and so can not interrupt itself because the interrupt enable flag is still set.

I suppose you want a solution but you are not going to like it.

Ditch the library and use your own code so that you can implement only a stop in the interrupt service routine and have the movement controlled by the loop function. This will involve a lot more code than you have.

In addition to what @GrumpyMike has said, you should just receive the IR data in the ISR and have code outside the ISR to deal with the stepper motor.

What stepper motor driver are you using?
Post a link to the datasheet for your stepper motor.

...R
Stepper Motor Basics
Simple Stepper Code

I'm using stepper motor 28byj-48 and motor driver uln2003. I'm just using example code from http://www.arduino.cc/en/Tutorial/StepperSpeedControl as reference. And I don't know how to implement my own code rather than the library provided :frowning:

And I don't know how to implement my own code rather than the library provided

Then you are some what stuffed. :confused:

I_am_not_a_robot:
And I don't know how to implement my own code rather than the library provided :frowning:

Then it sounds like a great time to learn. There are tons of tutorials around on how to make a stepper work.

There are tons of tutorials around on how to make a stepper work

You have been given two already, here is another two:-

Unipolar motors

Bipolar motors

My examples are not relevant for a 28BYJ stepper motor

…R

I found non blocking code for 28BYJ stepper motor here :28BYJ-48 Stepper Motor with ULN2003 driver and Arduino Uno – 42 Bots

I will try to coding it. Btw, thanx guys! :slight_smile:

I_am_not_a_robot:
I found non blocking code

I have not looked at your link but any code that moves the motor one step at a time can be written as non-blocking.

...R