|
|
View previous topic :: View next topic |
Author |
Message |
bigfalcon
Joined: 25 Mar 2008 Posts: 1
|
PWM Generation using PIC 18f4331 |
Posted: Tue Mar 25, 2008 2:19 pm |
|
|
We are trying to generate two PWM waves using PIC 18f4331. However, we have hard time figuring out how to change the duty cycle and period of the generated PWM wave. Could you please help us with the formula used by the power pwm functions to calculate the pwm period and duty cycle? Please find below the code we have developed to generate two PWM waves at the pin pwm0 and pwm2 of PIC 18f4331.
Code: |
#include <18f4331.h>
#fuses HS,NOWDT,NOPROTECT,BROWNOUT
#use delay(clock=20000000)
void main()
{
float duty_cycle1, duty_cycle2, period;
period = 16; //ms
duty_cycle1 = 10; //10%
duty_cycle2 = 10; //10%
while (1)
{
setup_power_pwm_pins(PWM_COMPLEMENTARY ,PWM_COMPLEMENTARY, PWM_OFF, PWM_OFF);
//Sets up PWM clock , postscale and period. Here period is used to set the
//PWM Frequency as follows:
//Frequency = Fosc / (4 * (period+1) *postscale)
setup_power_pwm(PWM_CLOCK_DIV_4|PWM_FREE_RUN,1,0,period,0,1,0);
set_power_pwm0_duty(duty_cycle1);
set_power_pwm2_duty(duty_cycle2);
}
} |
|
|
|
Ttelmah Guest
|
|
Posted: Tue Mar 25, 2008 3:58 pm |
|
|
First, use integers (int16) for your period, and duty values. There is no advantage to using floats, and a big cost, in terms of code size and speed. On my own PID servo implementations, and those published by MicroChip, you will find that everything is done in integer, because otherwise the speed cannot be achieved...
Now the key problem is to understand how the period, and the PWM duty cycle values affect one another. With the period set to 16, a duty cycle value of 10, will not give 10%, but 10/17 = 0.588 (58.8%)...
If you want the duty cycle values to count in 'percent', then your period, _must_ be 99. However you would normally want it to be something finer, like 0.1%, using a value of 999 for example.
With your period value at 16, the PWM frequency will be:
(20000000/4)/17 = 294117.64Hz
You refer to 'mSec'. Er. rather a difference....
If you wanted your period to be in mSec, then your total divider (prescale*(period+1)), would need to be 5000 (20000000/4/1000). Using a prescaler of 4, and period of 1249, is the only combination that gives this exactly. Then to give 10%, your duty cycle values, would need to be 125.
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|