View previous topic :: View next topic |
Author |
Message |
Ringo42
Joined: 07 May 2004 Posts: 263
|
How to calculate PWM freq |
Posted: Fri Aug 27, 2010 1:18 pm |
|
|
I know this has been discussed before, but I cannot find the thread. Can someone explain an easy way to calculate the values needed to set a specific freq on the PWM pins? I know it is setup_timer_2, but reading the CCS manual and the pic datasheet does not help alot.
I'm using a 452 or a 4520 at 20Mhz. I want to set up freqs from 1khz to 4khz. What I need is a simple explanation of what each of the three terms really mean. Prescale, period, and postscale.
Thanks
Ringo _________________ Ringo Davis |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
Ringo42
Joined: 07 May 2004 Posts: 263
|
|
Posted: Fri Aug 27, 2010 1:45 pm |
|
|
thanks guys, that is what I needed.
I made a little 1 line spreadsheet to help me out. Is there any way to post it here?
Ringo _________________ Ringo Davis |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
Ringo42
Joined: 07 May 2004 Posts: 263
|
|
Posted: Sat Aug 28, 2010 1:02 pm |
|
|
Can someone tell me what is wrong here? I get 1.2khz out, but it never changes to 4 khz. This is too simple to not work. What am I missing? Or can you not change the freq once it is set?
Ringo
Code: |
#include <18f452.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=20000000)
void main()
{
setup_ccp1(CCP_PWM);
setup_ccp2(CCP_PWM);
enable_interrupts(INT_TIMER2); // Timer 2 Overflow
enable_interrupts(global); // Enable IRQs
while(1)
{
setup_timer_2(T2_DIV_BY_16,255,1);//1.2khz //
set_pwm1_duty (498L);
set_pwm2_duty (498L);
delay_ms(1000);
setup_timer_2(T2_DIV_BY_16,77,1);// 4 khz
set_pwm1_duty (498L);
set_pwm2_duty (498L);
delay_ms(1000);
}
} |
_________________ Ringo Davis |
|
|
Ringo42
Joined: 07 May 2004 Posts: 263
|
|
Posted: Sat Aug 28, 2010 1:21 pm |
|
|
I guess it is something with my duty cycle. If I do this
Code: |
void main()
{
int x=0;
setup_ccp1(CCP_PWM);
setup_ccp2(CCP_PWM);
enable_interrupts(INT_TIMER2); // Timer 2 Overflow
enable_interrupts(global); // Enable IRQs
while(1)
{
for(x=255;x>70;x--)
{
setup_timer_2(T2_DIV_BY_16,x,1);//1.2khz //
set_pwm1_duty ((128));
set_pwm2_duty ((128));
delay_ms(100);
}
}
}
|
Then it starts out at 50% duty cycle, but they duty cycle goes up as the freq goes up until it is just high all the time. What is the calculation for 50% duty cycle at varying freqs?
Ringo _________________ Ringo Davis |
|
|
Ringo42
Joined: 07 May 2004 Posts: 263
|
|
Posted: Sat Aug 28, 2010 1:22 pm |
|
|
nevermind, got it, x/2. Makes perfect sense. _________________ Ringo Davis |
|
|
|