# PWM on PIC16F887 using CCS compiler acting weird

Status
Not open for further replies.

#### celegorn

##### Newbie level 5
Hello.

As the headline states, i am using PIC16F887 and i'm programming it with MPLAB, CCS compiler through Pickit 3. This is my code:
Code:
#include <16f887.h>
#use delay (clock=8000000)
unsigned int16 a,b;
#fuses HS,NOWDT,NOPROTECT,NOLVP
#define period 100
void main ()
{
a=1;
SET_TRIS_A(0);
SET_TRIS_C(0);
output_high(PIN_A5);                                   // Arbitrary bit
output_high(PIN_A4);                                   // Arbitrary bit
setup_ccp1(CCP_PWM);   	 			// Configure CCP1 as a PWM
setup_timer_2(T2_DIV_BY_4,period,1);

while(1)
{
if (a>=period) a=0;
set_pwm1_duty(a);
delay_ms(100);
a++;
output_toggle(PIN_A5);
}
}

My understanding is, that the variable a (i.e. duty cycle) should not exceed the period constant. Also, when a=period the PWM should output its maximum, i.e. 5 volts.

That's not the case as i have witnessed. I tried measuring the output of the PWM and it got as high as 1.09V. Also, i tried to limit the increase of variable a higher than period:
Code:
if (a>=300 a=0;

Doing this and measuring the PWM output i managed to get about 3.3V and further increasing the limit (at about 470) i got to about 4.63V where it peaked and stayed for a second and then reset back to zero.

What am i missing? Why does it not give me the full voltage (5V) when the duty cycle is equal to the period? Have i understood the whole thing wrongly?

Thanks.

#### FvM

##### Super Moderator
Staff member
Why not read the compiler manual? Please consider that when passing a 16-bit variable, the expected maximum pulse width value is 4*period. This is essentially a PIC hardware thing and not particularly related to CCS C. The CCS specific point is to scale 8-bit and 16-bit variables differently in the built-in function.

Writes the 10-bit value to the PWM to set the duty. An 8-bit value may be used if the most significant bits are not required. The 10 bit value is then used to determine the duty cycle of the PWM signal as follows:

· duty cycle = value / [ 4 * (PR2 +1 ) ]

The difference between 4.4 or 4.6 and 5V can be expected as a hardware effect of your (unknown) circuit.

Status
Not open for further replies.

Replies
0
Views
12K
Replies
0
Views
2K
Replies
4
Views
3K
Replies
7
Views
6K
Replies
2
Views
10K