8 years, 8 months ago.

What to know when the TimeOut function is over

Is the TimeOut posible to know when the Function is over?? like

include the mbed library with this snippet

Timeout flipper;

flipper.attach(&flip, 10.0); // setup flipper to call flip after 10 seconds
while(1)
{
    pc.printf("%d\r\n",flipper); // print flipper is howmuch time left
//or
    if(!flipper)
        pc.printf("Fucntion is Over");
}

Question relating to:

1 Answer

8 years, 8 months ago.

You can set a flag in the function to indicate it has completed.

Timeout flipper;
volatile bool flipped;

void flip(void) {
// your code
flipped = true;
}

main() {
  flipped = false;
  flipper.attach(&flip, 10.0); // setup flipper to call flip after 10 seconds
  while(!flipped)
  {
    // do something or nothing
  }

  // flip has finished.
}

Note that the flipped flag is marked as volatile, this tells the compiler to always check the value. Without it it could get clever and decide that since nothing in the while loop can change the value there is no need to check a second time. Forgetting to make something volatile can cause some very nasty bugs since sometimes the code will work fine and then you make a tiny change, the compiler optimizes things differently and things stop working.

As a general rule anything modified in an interrupt or timer that is then read in the main loop should be marked as volatile.

If you were to use a ticker rather than a timeout then instead of using a bool to indicate completion use a counter that you increase each time. The main code can then look for that value changing to indicate the timer running. That way you don't have to remember to constantly reset the flag in the main code.