CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

how to get PWM 40khz out

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
newpic



Joined: 09 Aug 2005
Posts: 32

View user's profile Send private message

how to get PWM 40khz out
PostPosted: Fri Apr 29, 2011 1:34 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Fri Apr 29, 2011 2:09 pm     Reply with quote

PWM frequency formula:
http://www.ccsinfo.com/forum/viewtopic.php?t=17993

Duty cycle formula:
http://www.ccsinfo.com/forum/viewtopic.php?t=42417&start=1
newpic



Joined: 09 Aug 2005
Posts: 32

View user's profile Send private message

40khz pwm to drive ultrasonic
PostPosted: Fri Apr 29, 2011 2:15 pm     Reply with quote

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)
   {
      
   }
}
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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