Will this PWM method work?
lardom
Posts: 1,659
I found a Phil Pilgrim code snippet I liked because it looks simple and to the point. I want to tweak it for a servo and again for a DC motor. Please tell me if my initial tweak is valid. Phil's original code is in the attachment.
dira[EscPin]~~ repeat waitcnt(cnt += clkfreq / 50) outa[EscPin]~~ waitcnt(cnt + pulse * clkfreq / 1_000_000) outa[EscPin]~
Comments
Regarding the code and PWM.
1. It appears to be for R/C servo control and to take one cog. Why so? Waitcnt dominates one cog and the 50Hz base frequency is for R/C control.
2. It doesn't actually limit the pulse within R/C control ranges of about 1.5ms to 2.5ms, so it may be adapted for longer duty cycles, like 50%
3. It is a good place to start in principal because it is so simple. Try it with an R/C servo and observe the response or try it with an LED. They explore modifications in rate.
And 4. There are actually two ways to do PWM [a] the sloppy way and the precise way.
The sloppy way is to add your pulse time to the overall frequency. The result is that the frequency wanders. Often the code is shorter and just fine for controlling lights.
The precise way is to have the on pulse and the residual time make the pulse trigger at exactly the same time on each cycle.
Can you figure out which one the above example is? If so, you are on your way and don't need any help. BTW, I may be wrong about the 50Hz. So you should doublecheck the Waitcnt math before trying this with a servo ;-D