I am generating PWM using timer 2 of PIC18f2420. I have 4MHz external clock crystal. The maximum frequency I can get from the PWM is 3.9KHZ with 1:1prescaler and postscaler. I need to get 100KHZ, any ideas? Will changing external oscillator to 20MHZ work?



You're looking at a frequency vs resolution trade-off.

The way this PWM works is to take your input clock and feed it into an 8-bit counter.
The clock fed to the counter is at most (for this series of PIC) your system clock divided by 4.
So in your case, the counter sees 1MHz.
An 8-bit counter has 256 steps, and if you're wanting to use the full resolution for your PWM duty-cycle, then that 1MHz clock is going to be divided by 256 to produce the final PWM frequency - giving you your 3.9kHz.

These PICs also allow you to get an extra 2 bits of resolution by tagging on the 2 bits from the system clock divider to give you an effective 10 bits or 1024 steps of PWM duty-cycle resolution.

The only way to get a higher PWM frequency with the same system clock is to reduce the resolution which the counter is giving you by setting its period register to a lower value.
So for instance if you set the period register to 100, then you can achieve a 10kHz PWM and of you set the period register to 10, then you'll get a 100kHz PWM.
But you need to realise that instead of the 1024-step resolution you had, you now have far fewer steps to adjust your PWM duty cycle.

Increasing your system clock to 20MHz will certainly help. You'll have to set your timer period register to 50 to achieve a 100kHz PWM frequency and you'll have 200 steps of duty-cycle resolution to play with.


The PWM period formula is given by the equation 15-1 on page 114 of the datasheet:

PWM Period = [(PR2) + 1] * 4 * Tosc *(TMR2 Prescale Value).

So if the prescaler is 1 and PR2 is 0, we get the minimal period (hence maximal frequency):

PWM Period = [0 + 1] * 4 * Tosc = 4*Tosc

So, the maximal frequency of PWM can be up to Fosc/4. In your case up to 1MHz (but, the higher is the frequency, the lower is PWM resolution). So the numbers you are showing are not correct. You should be able to get the required 100kHz frequency without a problem.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.