Wait for the end of a timer

Status
Not open for further replies.

michastro

Member
Hello,
I am working with a timer, and I want to wait until the timer has finished the current cycle. My code is very simple but doesn't work :-( And of course I don't understand why.
Thanks for your help.
Michel
Code:
#include "TeensyTimerTool.h"
using namespace TeensyTimerTool;

PeriodicTimer myTimer(PIT);
byte TimerEnd;

void printCurrentTime() {
  TimerEnd=1;
}

void setup() {
  delay(300);  
  TimerEnd=0;
  myTimer.begin(printCurrentTime, 5000ms, true);
}

void loop() {
  while (TimerEnd == 0) {
  }
  Serial.println("1 Cycle executed");
  exit(0);
}
 
timers and interrupts need a volatile variable if the variable is shared with the loop(). This tells the compiler that the variable can change at any time from many sources so it has to always be read and not cached, else the 2 source calls can read different result
 
Normally if your program reads the same variable more than once, you would want the compiler to perform only 1 read and keep the data in a CPU register so the next access is faster. That's exactly what the compiler does as it optimizes your code, of course when those precious few CPU registers aren't all needed by the surrounding code.

The volatile keyword forces every access to actually be performed. For normal variables it's a huge performance hit. But it's essential for hardware registers and variables written by interrupts.
 
Status
Not open for further replies.
Back
Top