View previous topic :: View next topic |
Author |
Message |
vinniewryan
Joined: 29 Jul 2009 Posts: 154 Location: at work
|
12f1822 PWM basic question |
Posted: Sat May 05, 2012 4:28 pm |
|
|
I'm trying to set up a pwm output of roughly 38Khz and I'm just a little confused about how to set up timer2.
In the data sheet, it says to set up and enable timer2 in order to start the PWM output. I've configured the PWM so this should be the last step.
My question is, will setting up timer2 values have any effect on the PWM output speed? Can I just use the following:
Code: | void main()
{
setup_timer2(T2_DIV_BY_1, 127, 1); //
set_timer2(0); //reset/initiate the timer???
} |
here's my code:
Code: |
#include <12f1822.h>
#use delay(clock=32000000)
#Fuses INTRC_IO,NOWDT,NOPROTECT,NOMCLR
#byte APFCON = 0x01 //CCP on RA5
#byte PR2 = 0xD2 // PR2
#bit T2CON = 1.0 // prescaler is 1 (1)
#bit T2CON = 1.1 // prescaler is 1 (1)
#use rs232(xmit=pin_a4,baud=4800,invert)
void main()
{
setup_oscillator(OSC_8MHZ | OSC_PLL_ON);
setup_ccp1(CCP_PWM); // Configure CCP1 as a PWM
set_pwm1_duty (50);
setup_timer_2(T2_DIV_BY_1, 127, 1); //
set_timer2(0); //reset/initiate the timer???
set_tris_a (0x2f); // 101111 (0=output) 5 4 3 2 1 0
PORT_a_PULLUPS(0x00); // 000000 (1=enabled) 5 4 3 2 1 0
while(1)
{
//test pwm output
}
}
|
This is my first PWM attempt so don't be too harsh :P _________________ Vinnie Ryan |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sat May 05, 2012 11:19 pm |
|
|
What's your compiler version ? |
|
|
Mike Walne
Joined: 19 Feb 2004 Posts: 1785 Location: Boston Spa UK
|
|
Posted: Sun May 06, 2012 3:17 am |
|
|
Like PCM programmer says, read the forum guide and supply ALL the relevant information.
Generally speaking, your code
Code: |
setup_timer2(T2_DIV_BY_1, 127, 1); //
|
Will generate a PWM frequency given by:-
PWM frequency = ( Fosc / 4) / (mode * period )
In your case that's
32MHz / 4 / 1 / (127 + 1) = 62.5 kHz
So, the simple answer is yes. Timer2 setup does affect PWM frequency.
Mike |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19535
|
|
Posted: Sun May 06, 2012 3:44 am |
|
|
Also, remember that as well as affecting the speed, it'll affect the range of numbers useable for the duty cycle.
Best Wishes |
|
|
vinniewryan
Joined: 29 Jul 2009 Posts: 154 Location: at work
|
|
Posted: Sun May 06, 2012 12:48 pm |
|
|
Perfect, thanks. Using your equation I figure 'mode' will need to be 210 in order to achieve as close to 38Khz as possible.
(32000000 / 4) / 1 / (210 + 1) = 37914.7 _________________ Vinnie Ryan |
|
|
|