code to generate PWM using PIC16F877A

Thread Starter

ctag06

Joined Jan 30, 2010
5
Hello everyone,

In my project, I have to design single phase inverter using PIC microcontroller 16F877A. The problem is, I don't know about the code to generate PWM using this PIC. Can anyone give me any sample of the source code to program my PIC?
 

Thread Starter

ctag06

Joined Jan 30, 2010
5
hello mic3
Thanks for reply me...I prefer to use picbasicpro in my project and MPASM as a asssembler.

Hai Alberto
Thanks for your reply and will try to do as you said. but in my project, i want to generate 18kHz pwm and i'll use 20MHz oscillator.
 

Tahmid

Joined Jul 2, 2008
343
With PR2=99 you will have 100% duty cycle with the above registers loaded with 400; 50% duty with 200 and 0% duty cycle with 0
I think that's wrong.
With PR2 = 99, you will have 100% duty cycle with CCPR1L loaded with 100, 50% duty with 50, 25% duty with 25 and 0% with 0.
It goes like:
CCPR1L value = (Required Duty Cycle (in %) / 100) * (PR2 + 1)
So, with PR2 = 29, you will have 20% duty cycle with CCPR1L = 0.2 * 30 = 6

Hope this helps.
Tahmid.
 

AlexR

Joined Jan 16, 2008
732
Tahmid;

You are correct.
I think Alberto must have been using a program call "Mister E PIC multi-cal" to get his figures. That program gives absolute rubbish output for PWM calculations and I have just deleted it from my PC.
 

Thread Starter

ctag06

Joined Jan 30, 2010
5
thanks to all...:)

That means, when i want to generate 18kHz PWM and using 20MHz oscillator and duty cycle is 50% is it right if i use to find PR2 using this equation:

(20MHz / (4 * TMR2 prescale value * 38KHz)) - 1= PR2.


*using TMR2 prescaler=1



By using the equation i get PR2=278 (approximately).

So, CCPRL1 value i get when PR2 = 278 is 139.5...Am i right?
 

AlexR

Joined Jan 16, 2008
732
Yep. that close enough.
On second thoughts NO!

PR2 is an 8 bit register so the maximum value it can take is 255!

To get 18KHz PWM from a 20MHz clock you have to use the 4:1 prescaler option
 
Last edited:

Thread Starter

ctag06

Joined Jan 30, 2010
5
Hai...
Thanks for your information. i'm really forgot 'bout that...so now, i should change the calculation part and put 4 as a TMR2 prescale value right? thanks a lot
 

symqwerty

Joined Feb 22, 2010
31
Other than previously discussed, it is possible to generate pwm without CCP module(PWM hardware) onboard. This is what we called software pwm. The method required you to write codes to generate the PWM rather than rely on the hardware. However, hardware(PWM) is more reliable compared to software version.

I'm not going to make you confuse here but just showing how colorful our world are..
 

Tahmid

Joined Jul 2, 2008
343
Hi ctag06,

For 20MHz, 18kHz PWM,
Rich (BB code):
Timer Prescale value = 4
PR2 = 69
CCPR1L = 35
Hope this helps.
Tahmid.
 
Top