Waiting for a variable to change

I have a program that will eventually be the low-level controller for a robot. In this program, I have an interrupt on Timer0 that takes care of driving the wheel motors using a PID algorithm that runs over many interrupts. I have a function that sets everything up for the ISR and starts things rolling (pun intended) by setting a boolean variable called "inMotion". The last thing that the interrupt routine does when the motion is done is to set inMotion to false. This code works and the motors move in the way that I intended BUT I am unable to detect when the motion is done from within loop() without doing something strange. An example is below:

void loop()
{  

  // Control the motors with ramping
  // This motion runs and completes.  I see a bunch of '.' and then 'A'.
  setupMotion(100, 300, 80, 8000);
  while(inMotion == true)
    {
    Serial.println(".");
    }
  Serial.println("A");

  // This motion runs and completes but I never see 'B' and it never goes back to the beginning of the loop.
  setupMotion(-20, -300, 500, 3000);
  while(inMotion == true)
    {
    }
  Serial.println("B");
}

I suspect that this is a compiler optimization problem. I'd really rather not print out a thousand periods while the motion is happening. How can I wait for the variable to change without having to put busy work inside of the while loop?

I think that
(This is just a snippet of my answer)

inMotion

How and where is inMotion declared ?
As its value is changed in the ISR is it declared volatile ?

Why did you not post a complete program that demonstrates the problem ?

Changing the variable to volatile did the trick! I had forgotten about that keyword.

Wow! Sure sounds like a bug in your code (which nobody here can see…).

Regards,
Ray L.

Seeing the code is overrated :slight_smile:

What you need is one of these