[En-Nut-Discussion] Problems when NutGetMills() is close to overflow?

Erik Lindstein erik at ledutveckling.com
Tue Feb 5 08:52:37 CET 2008


>>Erik Lindstein wrote:
>> First of all the documentation for the NutGetMills() should be updated.
>>
>> I guess there are two errors in there:
>> --------- From 4.4.0 -------
>> This function returns the value of a counter, which is incremented
>> every system timer tick. During system start, the counter is cleared
>> to zero and will overflow with the 32 bit tick counter (4294967296).
>> With the default 1024 ticks/s this will happen after ##### 7.9 years.
>> ##### The resolution is also given by the system ticks.
>>
>>If I am not totally mistaken the tickcounter will overflow after 49 days.
>>
>> I have some timeouts i use together with NutGetMillis().
>> Lets say i use it like this.
>>
>> uint32_t timeout = NutGetMillis() + 10000;
>>
>> for(;;)
>> {
>>        if(timeout <= NutGetMillis())
>>        {
>>                printf("Timeout - 10 Sec");
>>                timeout = NutGetMillis() + 10000;
>>        }
>>        NutSleep(100);
>> }
>>
>> If timeout overflows this timeout will occur directly in the next if
>> statement instead of the 10sec delay i expect.
>>
>> First i thought that NutGetMillis() would overflow after 7.9 years but
>> as that is not true i need to rewrite some of my code.
>> Anyone have some nice and clean code to handle this?
>
>Unsigned subtractions will do the trick.
>For example:
>
>uint32_t lastTick = NutGetMillis();
>
>for(;;)
>{
>       if(NutGetMillis() - lastTick > 10000)
>       {
>              printf("Timeout - 10 Sec");
>                lastTick = NutGetMillis();
>        }
>        NutSleep(100);
>}
>
>Greetings,
>       Andreas

Thank you very much Andreas.

A problem for me with that solution is that i will need to use two
variabels for each timeout.
I have a couple of timeouts that i set in different threads and it
would be nice if i could use only one uint32_t to handle each
timeout(but perhaps that's not possible)
With your solution i would need to use one uint32_t(lastTick) and one
uint16/32_t(10000) extra variable for the delay time, that i needs to
be variable.

Well perhaps i can live with that :-)

Regards
--
/Erik



More information about the En-Nut-Discussion mailing list