Pulse width modulation using PIC


Pulse-width modulation (PWM) or pulse-duration modulation (PDM), is a modulation technique that conforms the width of the pulse, the pulse duration, based on modulator signal information.

  • Although this modulation technique can be used to encode information for transmission, its main use is to allow the control of the power supplied to electrical devices, especially to inertial loads such as motors.
  • The term duty cycle describes the proportion of ‘on’ time to the regular interval or ‘period’ of time.
  • A low duty cycle corresponds to low power because the power is off for most of the time.
  • The duty cycle is expressed in percent, 100% being fully on.
  • By changing the width of the pulse applied to the DC motor we can increase or decrease the amount of power to the motor and increase or decrease the motor speed.

Generating PWM

  • In PIC Microcontrollers CCP Modules are available which can be used to generate PWM waves.
  • CCP Stands for Capture/Compare/PWM.

CCP Capture/Compare/PWM Modules

  • PIC 16F877A has two CCP modules named as CCP1 and CCP2.
  • Each CCP module has a 16 Bit register which can operate as :
    1. 16 Bit Capture Register
    2. 16 Bit Compare Register
    3. PWM Duty Cycle Register.


  • It generates a 10-bit resolution PWM output.
  • CCP1 and CCP2 output are multiplexed with PORTC.
  • CCP1 and CCP2 modules uses Timer 2 for their operation.
  • The period of generated PWM waves is determined by the value in the PR2 register.
  • The comparator compare the value of Timer 2 and PR2 every-time.
  • When these values become equal:-
    Timer 2 will be reset and output will become HIGH.
  • The duty cycle is determined by the value in CCPR1L and CCP1CON.
  • These registers can be written at any time.
  • The duty cycle value is latched to CCPR1H.
  • A 2-bit internal latch when there is a match between Timer 2 and PR2.
  • This is done to avoid the glitches in the PWM output.
  • The value in CCPR1H and 2-bit internal latch is compared with Timer 2.
  • When a match occurs output will become LOW.
  • The maximum PWM resolution can be found using.
  • PWM Period Formula:-
  • PWM Duty Cycle can be found using:-

PWM Wave Form


 void main()
 short duty1 = 12;
 TRISB = 0xFF;
 TRISC = 0x00;
 while (1)
 if (PORTB.F0==0)
 if (PORTB.F1==0)