title: How to deal with a wrapping counter in embedded C
body: <p>I need to deal with a counter that gives me ticks for my application. The counter is 32bits so what I need to know is how to deal with it when it wraps. for example:</p>
  <p>I have a function that returns a <code>(timestamp + shifttime)</code> and I have another function that will return 1 or 0 depending whether or not the time has elapsed, but there is a possibility that that my counter will wrap how, do I deal with this?</p>
  <hr />
  <p>Thanks a lot for all the responses guys. I will give more detail in this edit.</p>
  <p>I am using the STM32 Cortex-M3. I wanna use the RTC counter to use it as the tick for my application to schedule tasks that need to happen at certain intervals. The RTC can generate an overflow interrupt so it's not a problem to detect the interrupt. the main problem that I have (or at least I think is a problem) is when certain tasks gets a <code>(timestamp+shift)</code> i.e.</p>
  <pre><code>int main( void )
  {
      FlashLedTimeStamp = ReturnCounter( 20 );  // currentcounter value + a shift of 20
      StatusLedTimeStamp = ReturnCounter( 3 );  // currentcounter value + a shift of 3
  
  // then later on ....
  while(1)
  {
      /* other tasks could go here */
  
      if( HasTimeElapsed( FlashLedTimeStamp ) )
      {
         /* do something and get another timestamp value */
         FlashLedTimeStamp = ReturnCounter( 20 );  // currentcounter value + a shift of 20
      }
      
      if( HasTimeElapsed( StatusLedTimeStamp ) )
      {
         /* do something and get another timestamp value */
         FlashLedTimeStamp = StatusLedTimeStamp( 3 );  // currentcounter value + a shift of 3
      }
  }   
  }
  </code></pre>
  <p>Lets assume that my RTC counter is only 8 bits long to make the math easy.</p>
  <p>If my current counter is at 250 when I get my timestamps that means that <code>FlashLedTimeStamp = 14</code> and <code>StatusLedTimeStamp = 253</code> how would I check to see that <code>FlashLedTimeStamp</code> has expired??</p>
  <p>keep in mind that I don't necessarily check all the time to see what the current counter is and whether or not certain timestamps have expired.  I hope this makes it clear what the problem I have is.</p>