Embedded C program for Generating PWM signal for servo motor/DC motor in PIC18F using MPLAB IDE

Program:

/*      Calculations
 * Fosc = 48MHz
 *
 * PWM Period = [(PR2) + 1] * 4 * TMR2 Prescale Value / Fosc
 * PWM Period = 200us
 * TMR2 Prescale = 16
 * Hence, PR2 =  149 or 0x95
 *
 * Duty Cycle = 10% of 200us
 * Duty Cycle = 20us
 * Duty Cycle = (CCPR1L:CCP1CON<5:4>) * TMR2 Prescale Value / Fosc
 * CCP1CON<5:4> = <1:1>
 * Hence, CCPR1L = 15 or 0x0F
 */
//#include<p18f4550.h>
#include<xc.h>
//unsigned char count=0;
//bit TIMER,SPEED_UP;
void main(void)
{
    unsigned int i;
   
    TRISCbits.TRISC2    = 0;            //CCP1 pin as output
   
    CCP1CON  =   0b00101100;            //Select PWM mode; Duty cycle LSB CCP1CON<4:5> = <1:1>
   
    T2CON   =   0b00000010;             //Prescalar = 16; Timer2 OFF
    GIE=1;
    TRISAbits.TRISA4=0;
    while(1)
    {
        TMR2=0;
        PR2     =   250;  
        CCPR1L   =   2;                //Duty cycle 1%
       
        TMR2IF=0;
        TMR2ON = 1;                         //Timer2 ON
        for(int i=2;i<255;i+=50)
        {
            CCPR1L=i;
            for(int j=0;j<1000;j++)
                for(int k=0;k<10000;k++);
                LATAbits.LATA4=~LATAbits.LATA4;
        }
    }
}

Output:




Previous
Next Post »