Hacker News new | ask | show | jobs
by klingonopera 2585 days ago

  > "Side note: although at first glance this code looks like it fails to account for the case where TCNT1 overflows from 65535 to 0 during the timing run, it actually works properly for all durations between 0 and 65535 ticks."
From example 1, ignoring device and setup-specifics what to do when TCNT1 overflows, it actually works properly for all ticks, both "first" and "second" are unsigned (therefore behaviour is defined), and the delta between them both is always between 0 and 65535, no matter what values they may have, and also correct in all cases.

E.g.:

  timeDelta = timeStampNow - timeStampLast = 0 - 65535 = 1
2 comments

But if the duration is > 65535 ticks, the calculated duration will be wrong, no? There is no mechanism to count how many times TCNT1 overflows, so it will be incorrect if the duration of what you are timing exceeds 65535 ticks.
That is correct, yes. I had erroneously understood that the author meant "all durations between 0 and 65535 ticks" as "any duration between the device's 0th and 65535th tick", my bad... Also makes this entire thread obsolete, but FWIW, one shouldn't be attempting to measure a duration that can't even be contained in the variable's bit width. Some workarounds would be to add more bits, slow down the tickrate or add overflow counters.
Can someone please tell me why this got downvoted? It's particularly annoying when correcting common misconceptions to get penalised for it... (and if what I said was wrong, I'd also like to know why!)
Probably because the article already says it works for all ticks...
Yes, upon rereading I see that, too. When I first read it, I understood in such a way that it only would work until (a timestamp of) 65535 ticks since device-startup had passed, but he was referring to durations of that length.

Thank you for clarifying.