View Full Version : Spin CNT Help Needed

hippy

09-16-2007, 09:16 AM

I am having no end of trouble trying to get my head round solving this, so any help would be gratefully received ....

timeout := ( clkfreq / 1000 ) * mS + CNT

repeat

if timeout > CNT

NotTimedOut

else

TimedOut

It will work fine if 'timeout' and CNT are positive, but it does not handle all cases of CNT wrapround and overflows. The solution maybe obvious, but I cannot see it.

Lawson

09-16-2007, 11:41 AM

how about testing for

(timeout - CNT) > 0

the subtraction should be more tolerant of overflows than the greater than test.

My 2 cents

Marty

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Lunch cures all problems! have you had lunch?

deSilva

09-16-2007, 01:03 PM

This is how it works:

+ 2^31 <------- C -------- 0 -------- TOUT -- > -2^31

..> ..........> .....

Starting with: timeout > CNT.

subtracting "CNT" from both side gives "Lawson's formula"

You see in the diagram, that this "moves" CNT to the center = 0, now "timeout" can easily be found

either at the + (still time left) or the - (time out!) side.

This works as long as ||(timeout-CNT) < 2^31 ticks.

Post Edited (deSilva) : 9/16/2007 6:09:44 AM GMT

hippy

09-16-2007, 04:02 PM

Thanks both, it took a bit of paper working to convince myself that would work, but I believe that solves the problem.

deSilva

09-16-2007, 06:13 PM

hippy said...

Thanks both, it took a bit of paper working to convince myself that would work, but I believe that solves the problem.

I intended to save you the paperwork through my diagram http://forums.parallax.com/images/smilies/smile.gif

An even better diagram would show a circle where +/- 2^31 meet,opposite to zero - so a subtraction (or addition) is a "turn of that wheel"

hippy

09-17-2007, 12:28 AM

deSilva said...

I intended to save you the paperwork through my diagram http://forums.parallax.com/images/smilies/smile.gif

And it was appreciated. It wasn't that your answer caused any problems, just that I needed to to do the working out to make myself understand and assure myself that the theory held up to practice. Thanks, it does.