Generating PWM with PIC18F4520
In this tutorial we will see how to generate the PWM signals using PIC18F4520.
Contents
[hide]Prerequisites
Please check this tutorial for detailed explanation on PIC18F4520 PWM module.
PIC18F4520 PWM Module
PIC18F4520 microcontroller has two independent CCP(Capture/Compare/PWM) modules, named as CCP1 and CCP2. Each CCP module has two 8-bit resistors(CCPxH,CCPxL) that can be use as:
- 16 bit Capture Register
- 16 bit Compare Register
- 10-bit PWM Register.
In this tutorial we will be discussing only the PWM part of CCP. PIC has 2PWM module with a resolution of 10-bits.
Below tables shows the PWM module of PIC.
PWM Channel | Port Pin | Control Register | Duty Cycle Register | Period Register |
---|---|---|---|---|
PWM1 | PC.2 | CCP1CON | CCPR1L | PR2 |
PWM2 | PC.1 | CCP2CON | CCPR2L | PR2 |
Code1
Below is the example to vary the brightness of the LED(PC.2) using PWM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "pwm.h" | |
#include "delay.h" | |
/* start the main program */ | |
int main() | |
{ | |
int dutyCycle; | |
PWM_Init(0); /* Initialize the PWM module and the Cycle time(Ton+Toff) is set to 100*/ | |
PWM_Start(0); /* Start PWM signal generation on Selected pin */ | |
while(1) | |
{ | |
for(dutyCycle=0;dutyCycle<100;dutyCycle++) /* Increase the Brightness of the LED */ | |
{ | |
PWM_SetDutyCycle(0,dutyCycle); | |
DELAY_ms(5); | |
} | |
for(dutyCycle=100;dutyCycle>0;dutyCycle--) /* Decrease the Brightness of the LED */ | |
{ | |
PWM_SetDutyCycle(0,dutyCycle); | |
DELAY_ms(5); | |
} | |
} | |
} |
Code2
Progarm to generate the PWM signals of 25% & 75% duty cycle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "pwm.h" | |
#include "stdutils.h" | |
/* start the main program */ | |
int main() | |
{ | |
PWM_Init(0); // Initialize the PWM modules | |
PWM_Init(1); | |
PWM_SetDutyCycle(0,25); //Set the Duty Cycle of 25% for PWM1->RC2 | |
PWM_SetDutyCycle(1,75); //Set the Duty Cycle of 25% for PWM2->RC1 | |
PWM_Start(0); //Start the PWM signal generation | |
PWM_Start(1); | |
while(1); | |
} |