This PIC16F877 microcontroller tutorial provides the 2 channel PWM code (using C language) and Proteus simulation ( written using MPLAB and HI-TECH C compiler ). There are many uses for PWM signal, e-g you can control dc motor speed using PWM. CCP
is the name for the built in PWM module in PIC16F877. There are 2 built
in PWM modules available, namely CCP1 and CCP2. This code is using both
CCP1 and CCP2 modules to generate 2 separate PWM signals.
The following diagram (made in Proteus) shows the PWM generator circuit diagram.
|
Figure 1. PIC16F877 PWM generation circuit |
A crystal of 20MHz is used here with PIC16F877. As we know that any PIC
micro controller has an architecture which executes an instruction in 4
CPU cycles, hence this 20Mhz crystal makes this PIC16F877 run at 5MIPS
(Million of instructions per second). In the above figure, it is clear
that a PWM of 4.9kHz frequency with 50% duty cycle is being generated
at
RC2/CCP1 pin and a PWM of 4.9kHz frequency with 75% duty cycle is being generated at
RC1/CCP2 pin.
Code
The code for main function is shown below.
|
Figure 2. Main code for PIC16F877 PWM |
In the main function, PWM is initialized using the '
InitPWM()' function. Then PWM duty cycle is set to 50% on CCP1 module and 75% on CCP2 module ( You can verify this value from
Figure 1 ).
After that microcontroller is free and built in CCP1, CCP2 modules
automatically generates desired PWM frequencies. When you need to change
PWM duty cycle, then just call
SetPWMDutyCycle() function and
change the duty cycle as per requirement. You can pass a value of 0(0%
duty cycle) to 255(100% duty cycle) in the arguement of
SetPWMDutyCycle() function.
The code for
InitPWM() function is shown below.
|
Figure 3. InitPWM function code for PIC16F877 |
InitPWM() function initializes the PWM module CCP1 and CCP2 to generate PWM signal at 4.88KHz using '
Timer 2'. RC2 ( Pin 17 ) gives the output of the CCP1 module and RC1 ( Pin 16 ) gives the output of the CCP2 module.
The code for '
SetPWMDutyCycle()' function is shown below.
|
Figure 4. SetPWMDutyCycle function code for PIC16F877 |
Downloads
2 channel PWM code using PIC16F877 was compiled in MPLAB v8.85 with
HI-TECH C v9.83 compiler and simulation was made in Proteus v7.10.
To download code and Proteus simulation click here.
Source : web