Calculating milliseconds with CNT
eagletalontim
Posts: 1,399
Not sure if I am doing this correctly or not, but I just want to verify the best way to count milliseconds using CNT :
PUB MillisecondsInASecond | cnt1, cnt2 repeat cnt1 := cnt waitcnt(clkfreq / 1000 * 10 + cnt) cnt2 := cnt milliseconds := cnt2 - cnt1
Comments
The milliseconds := cnt2 - cnt1 should be :
milliseconds := (cnt2 - cnt1) / (clkfreq / 100)
That would be deciseconds (1/100 seconds). Milliseconds would be (cnt2 - cnt1) / (clkfreq / 1000)
It appears that your spacing is being lost while posting. The line "count1 := 0" is at the same indentation level as the "if updated == 0", and the "count++" is at the repeat level, among other things. I assume everything below the repeat is supposed to be part of the repeat block.
SPIN is really calculating this during runtime, so you could better say:
waitcnt( constant(clkfeq / 1000 * 10) + cnt )
This way the calculation of clkfreq / 1000 * 10 is done by the compiler.
Same is true for the pulsewidth! (clkfreq / 10000) won't change during runtime, so make it a constant(clkfreq / 10000).
Jonathan
The "||" isn't needed. The signed 32-bit math takes care of it for you.
If you had no code between the two lines you would end up with 0 -- what you want. The value in elapsed is in system ticks. You can convert to milliseconds by dividing by clkfreq/1000. There's a cleaner way, I believe, so long as you're not changing clock speed on-the-fly. I have this CON block in all my programs.
It provides constants for the clock frequency (80MHz in my case) and the number of ticks in a millisecond and microsecond. If you're not changing clock speed on-the-fly then using these constants will help you improve the speed of your program by eliminating some inline calculations.
In your case you *might* do something like this:
Of course, another thing you can do is arm a counter for positive input and let it accumulate the ticks for you. Converting ticks to milliseconds is the same.