Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 7 of 7

Thread: Wait for the end of a timer

  1. #1

    Wait for the end of a timer

    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);
    }

  2. #2
    Senior Member
    Join Date
    Nov 2012
    Posts
    1,734
    TimerEnd needs to be declared as volatile
    Code:
    volatile byte TimerEnd;
    Pete

  3. #3
    Thank you, it was simple, but I didn't know that.
    Michel

  4. #4
    Is it possible to explain me why the volatile variable works and not a standard variable??

  5. #5
    Senior Member
    Join Date
    Dec 2016
    Location
    Montreal, Canada
    Posts
    3,868
    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

  6. #6
    OK thank you!!

  7. #7
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    25,026
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •