# Creating a PWM signal using PIC18F4520

I am trying to create a 100ms period pwm signal (10Hz) with a PIC18F4520, I followed the PR2 equation to help me create this signal

I have a 20MHz clock frequency with a prescaler of 16 and a PWM period of (100 x 10-3 s) and when I use these values in this equation:

$\Large PR2 = ( \frac{PWM Period}{( TOsc \times 4 \times TMR2 Prescaler )} ) - 1$

I get 0x31249

I am also trying to run this PWM signal at 50% duty cycle [so 50ms off and 50ms on] by using the duty cycle equation:

Duty Cycle = ((CCPR1L << 7 ) | (CCP1CON bits <5:4>) ) $\times$ TOSC in MHz $\times$ Prescale

Which gives 62500 as a value for the duty cycle.

This whole exercise is for me to learn better about using PWM signals. I am programming the PIC in C18 and simulating it on PROTEUS VSM.

that is a picture of what the oscilloscope is picking up off the PWM signal which DOES NOT LOOK LIKE 50% duty cycle or 10 Hz frequency.

This is the code that I am using on PROTEUS VSM:

include p18cxxx.h
include pwm.h
include timers.h
pragma config OSC = HS
pragma config MCLRE = ON
pragma config WDT = OFF
pragma config LVP = OFF
pragma config DEBUG = OFF
pragma config PBADEN = OFF
unsigned char period = 0x31249;         // assign PR2 to 31249 used to get 100ms period

unsigned int duty_cycle = 62500;  // used to get 50ms on/off

void main(void)
{

OpenTimer2(TIMER_INT_OFF & T2_PS_1_16 & T2_POST_1_1);

OpenPWM1 (period);

SetDCPWM1 (duty_cycle);

while (1);

}

As it can be seen I am using the PWM library as I heard it was easier to work with.

I am sorry if I appear too unacquainted with how questions are made on this forum or as to how I presented my problem.

• unsigned char period = 0x31249; That value is far too big for an unsigned char, which is possibly part of the problem. Commented Aug 13, 2015 at 14:28
• Even I thought it was way too big and I went with it only not to work , have you got a different value than that? If you do how did you get it? Commented Aug 13, 2015 at 14:38