Counters
Cenlasoft
Posts: 265
Hello,
Jon Williams was kind enough help me with the following code:
Pub Main
USTx(0)
Pub USTx(pin) | t
ctra[30..26] := %00100 'set PWM for counter A
ctra[5..0] := pin
frqa := 2_147_483 '40 khz at 80 mhz
dira[pin]~~
t := cnt
repeat
outa[pin]~ ' allow modulation`
waitcnt(t += (clkfreq / 1_000_000 * 500)) ' on 0.5ms
outa[pin]~~ ' kill modulation
waitcnt(t += (clkfreq / 1_000 * 18)) ' off 19.5ms
I change a few things but, my question is: frqa := 2_147_483 makes the frequency 40khz and I think it's obtained by dividing 80_000_000 by a number (2_147_483). I read alot about counters but, could someone explain this for me? The original purpose was to get PWM a 40khz frequency with a pulsewidth of .5 ms and to repeat every 20 ms. It works, but I need some clarifaction.
Thanks,
Curtis
Jon Williams was kind enough help me with the following code:
Pub Main
USTx(0)
Pub USTx(pin) | t
ctra[30..26] := %00100 'set PWM for counter A
ctra[5..0] := pin
frqa := 2_147_483 '40 khz at 80 mhz
dira[pin]~~
t := cnt
repeat
outa[pin]~ ' allow modulation`
waitcnt(t += (clkfreq / 1_000_000 * 500)) ' on 0.5ms
outa[pin]~~ ' kill modulation
waitcnt(t += (clkfreq / 1_000 * 18)) ' off 19.5ms
I change a few things but, my question is: frqa := 2_147_483 makes the frequency 40khz and I think it's obtained by dividing 80_000_000 by a number (2_147_483). I read alot about counters but, could someone explain this for me? The original purpose was to get PWM a 40khz frequency with a pulsewidth of .5 ms and to repeat every 20 ms. It works, but I need some clarifaction.
Thanks,
Curtis
Comments
2_147_483 = 4_294_967_296 * 40_000 / 80_000_000
It is an angular frequency. Kind of like expressing frequency as radians or brads per second instead of full cycles per second.
If you divide 4_294_967_296 / 2_147_483 = 2000
That is how many times the frqa is added to the phase accumulator phsa before it overflows and rolls back to zero. That is one complete cycle. To put it another way, it adds 1/2000 of the full circle at each Prop clock tick, once every 12.5 nanoseconds.
2000 * 12.5E-9 = 0.000025 second
That is how long it takes phsa to pass through one complete cycle. And...
1 / 0.000025 = 40_000 hertz.
I now understand it. Thanks again.
Curtis