Saturday, June 18, 2011

Example of how to generate PWM in mikroC using the CCP module

//Program to generate 40kHz output at RC2(CCP1) pin
//Microcontroller: Microchip PIC18452
//Language: C
//Compiler: mikroC v8.20
//Programmer: Tahmid

void main (void){
     TRISC = 0;
     PORTC = 0;
     ADCON1 = 7;
     T2CON = 0;
     TMR2 = 0;
     PWM1_Init(40000); //40kHz
     PWM1_Change_Duty(128); //50% duty cycle
// Choose Duty cycle as such:
// PWM_Change_Duty(x);
// x = ( (Duty Cycle in %) / 100) * 255
     PWM1_Start(); //Start PWM
     while (1){ //Loop forever
// Whatever else might be needed to be done while PWM is running

In mikroC, you set the duty cycle by using the function PWM1_Change_duty(x). The value you put within the parentheses (x) has to be between 0 and 255. 0 means 0 duty cycle, 255 means 100% duty cycle, so 128 means 50%.

You get PWM output at RC2 (pin 17).


  1. And how do i output the PWM signal to a PWM pin?

  2. The PWM signal is automatically output to the PWM pin.

  3. i want to control the dc motor through can i code it without using mikroc library?

  4. how can i split this pwm in to two pins as one is others inverse to drive a power inverters mosfets.

  5. Sir,
    During build file I'm getting error at PWM1_Init(40000);
    Uncleared identifier

    Please help

  6. how to generate 5 pwm gating signals for pic16f877a .i want code for this plz hlp.....

  7. can u tell me how to generate pwm using eccp module which is present in pic18fxxx....plz reply

  8. hi dear its very nice and very helpful post for those who are new and thinking to start a blog site.Your posts are very helpful and creative. I have atlast opened a blog site being inspired from your articles clik here and see about inverter