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:
I h
Assuming you're dealing with unsigned types, you can check for wrapping pretty easily --
if (timestamp + shifftime < timestamp)
it_wrapped();
Cast the result of unsigned subtraction to signed and compare to zero. Should handle overflow when you check it often enough (and your timeout is less than half the range of your timer).
uint32_t timer( void); // Returns the current time value
uint32_t timeout;
timeout = timer() + offset;
// wait until timer() reaches or exceeds timeout value
while ((int32_t)(timeout - timer()) > 0);
The simplest way to do this is to make an "epoch counter", that explicitly counts rollovers. (Example: you have a hardware counter that counts seconds 0..59. Your epoch counter would count minutes, by incrementing each time it noticed that the seconds counter had rolled over.)
Your future_scheduler function then reads the current epoch and time,and computes a new epoch and time for your event.
Alternatively, you could just punt, and make your timing function count your event schedules down to zero on each timer tick.
I think one of the easiest ways to do this, would be to have another counter (lets call it Wrap counter, let this be a static global for the timer module), count up each time your original 32 bits counter wrapped.
In the function where your counter is ticking away, everytime this counter reaches its maximum count, you have your Wrap counter increment. So when you are reading the function which returns whether or not the timer has elapsed, you also read the Wrap counter, to check how many times it wrapped over. The important thing is, to also do this: everytime you read the wrap counter, you want to clear it, for your next reading.
lets assume the counter counts down (many count down to save on gates in the logic).
you need to first know the period of time it takes to get to 2^32 ticks and need to insure that you are well oversampling that.
If you want to find the time period between two events, say start and end
start = read timer lasttime = start rollover = 0
while waiting for thing to happen
nowtime = read timer if(nowtime>lasttime) rollover+=1 (this is a down counter) lasttime = nowtime
event happens: end = read timer
total time = start - end (this is a down counter and note that this math works even when rolling over)
total time = total time/ scaling factor to get from ticks to seconds, minutes, whatever total time += rollover * seconds/minutes/whatever per 2^32 counts
if you have an up counter then nowtime
If you can guarantee that your event will happen within 2^32 counts you dont need to do the rollover now time last time thing you only need start and end and the total ticks = start - end will work even if the counter rolls from 0x00000000 to 0xFFFFFFFF between start and end.