Referring to a variable found in an Interrupt from a loop function

Hi, I'm trying to refer to the variable 'encoder0Pos from the interrupt, so that when it reaches a certain value, the stepper motor stops rotating. The problem I found is that the value of the variable is 0 and although it's changing in the interrupt, I need to use it in the loop function. Can anyone help please?

#include <Stepper.h>
#define encoder0PinA  2
#define encoder0PinB  3

volatile unsigned int encoder0Pos = 0;

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8,9,10,11);

void setup()
{
  pinMode(encoder0PinA, INPUT); 
  digitalWrite(encoder0PinA, HIGH);
  pinMode(encoder0PinB, INPUT); 
  digitalWrite(encoder0PinB, HIGH);
  
  myStepper.setSpeed(100); 

  attachInterrupt(0, doEncoder_Expanded, CHANGE);
  Serial.begin (9600);
}

void loop()
{
  myStepper.step(stepsPerRevolution);

  if (encoder0Pos == 3143)
  {
    myStepper.step(0);
  }
}

void doEncoder_Expanded(){
  if (digitalRead(encoder0PinA) == HIGH)
  {
    if (digitalRead(encoder0PinB) == LOW) 
    {
      encoder0Pos = encoder0Pos - 1;
    } 
    else
    {
      encoder0Pos = encoder0Pos + 1;
    }
  }
  else 
  { 
    if (digitalRead(encoder0PinB) == LOW)
    { 
      encoder0Pos = encoder0Pos + 1; 
    } 
    else
    {
      encoder0Pos = encoder0Pos - 1;

    }
  }
  Serial.println (encoder0Pos); 
}

The first thing to do is not to print inside the ISR. Printing depends on interrupts and they are disabled when in an ISR. What do you see if you print it in loop() ?

If I print it in loop, the value remains 0.

Hi again, I think I managed. I tried to do it in the loop again, and I found a change in the value.

Thanks a lot for your help.

Where, in loop(), are you printing it? The Stepper::step() method is a blocking function. It will not return until the number of steps that it was supposed to take has been reached. Checking the position of the encoder at that point seems pointless.

Using an encoder, the idea is to step, check, step, check, etc. until the motor is at the desired position.

Hi,

Do you mind helping me with the step, check, step, check because I can't figure it out.

Thanks.

Do you mind helping me with the step, check, step, check because I can't figure it out.

The loop() function is called over and over, so the repeat part is handled.

For the rest, if the encoder value is lower than the desired end position, step(1). If it is higher than the desired end position, step(-1). That's simple enough, isn't it?

Yes makes sense. Thanks a lot.

Read encoder0pos into a temporary variable in loop() and do your calculations with the temporary variable. You should briefly stop the interrupts while you read the value

noInterrupts();
  tempEncoder0pos = encoder0pos;
interrupts();

If you are subtracting values from encoder0pos prehaps it should be a signed variable.

...R