|
|
View previous topic :: View next topic |
Author |
Message |
newpic
Joined: 09 Aug 2005 Posts: 32
|
how to get PWM 40khz out |
Posted: Fri Apr 29, 2011 1:34 pm |
|
|
I use timer2, try to get 40khz out to drive an ultrasonic sensor.
Can anybody help?
Code: | #include <16f877.h>
#fuses XT, NOWDT, NOPROTECT, NOBROWNOUT, NOPUT, NOLVP
#use delay(clock=4000000)
void main()
{
output_low(PIN_C1); // Set CCP2 output low
setup_ccp2(CCP_PWM); // Configure CCP2 as a PWM
setup_timer_2(T2_DIV_BY_16, 124, 1); // 500 Hz
set_pwm2_duty(31); // 50% duty cycle on pin C1
while(1)
{
}
} |
Code: | setup_timer_2(T2_DIV_BY_16, 124, 1); // 500 Hz |
what do I need to set here to get 40khz out? Explaination will helpful. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
newpic
Joined: 09 Aug 2005 Posts: 32
|
40khz pwm to drive ultrasonic |
Posted: Fri Apr 29, 2011 2:15 pm |
|
|
I got it. here is the new code
Code: | #include <16f877.h>
#fuses XT, NOWDT, NOPROTECT, NOBROWNOUT, NOPUT, NOLVP
#use delay(clock=4000000)
void main()
{
output_low(PIN_C1); // Set CCP2 output low
setup_ccp2(CCP_PWM); // Configure CCP2 as a PWM
setup_timer_2(T2_DIV_BY_1, 24, 1); // 40kHz
/*
Crystal Frequency
PWM Freq = -----------------------------------------
(PR2 + 1) * (Timer2 Prescaler) * 4
** I need 40000 (40khz), so I need a number that 4000000 / x = 40000
so x is 100. I need to get a number (a+1)*4 = 100
a = is 24; which is (24+1)*4 = 100.
* to get duty cycle, .25 * 24 = 6,
*/
set_pwm2_duty(6); // 25% duty cycle on pin C1
while(1)
{
}
} |
|
|
|
|
|
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
|