# simple PWM design on PIC16F877A using ccs c compiler

Status
Not open for further replies.

#### youngjkoh

##### Newbie level 3
Hi, i'm new to the programming and I was trying to set up the a/d converter. I found this pwm example code from ccs examples, and I was expecting pinC7 as an analog input and the picC6 as a modulated output. However, when I checked the output on the oscilloscope it looked like it is not dependent on what input I put in C7! It looked like it goes high whenever Vcc is high... I don't understand.. Can anyone help me explaining it? Also, I was wondering how the timer works, and why we need it. Why is period=127? Thank you!

Code:
#if defined(__PCM__)
#include <16F877A.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, BRGH1OK)  // Jumpers: 8 to 11, 7 to 12

void main() {
char selection;
byte value;

printf("\r\nFrequency:\r\n");
printf("    1) 19.5 khz\r\n");
printf("    2) 4.9 khz\r\n");
printf("    3) 1.2 khz\r\n");

do {
selection=getc();
} while((selection<'1')||(selection>'3'));

setup_ccp1(CCP_PWM);   // Configure CCP1 as a PWM

//   The cycle time will be (1/clock)*4*t2div*(period+1)
//   In this program clock=20000000 and period=127 (below)
//   For the three possible selections the cycle time is:
//     (1/20000000)*4*1*128 =  25.6 us or 39.062 khz
//     (1/20000000)*4*4*128 = 102.4 us or 9.765 khz
//     (1/20000000)*4*16*128= 409.6 us or 2.441 khz

switch(selection) {
case '1' : setup_timer_2(T2_DIV_BY_1, 127, 1);
break;
case '2' : setup_timer_2(T2_DIV_BY_4, 127, 1);
break;
case '3' : setup_timer_2(T2_DIV_BY_16, 127, 1);
break;
}

setup_port_a(ALL_ANALOG);
printf("%c\r\n",selection);

while( TRUE ) {

printf("%2X\r",value);

set_pwm1_duty(value);          // This sets the time the pulse is
// high each cycle.  We use the A/D
// input to make a easy demo.
// the high time will be:
//  if value is LONG INT:
//    value*(1/clock)*t2div
//  if value is INT:
//    value*4*(1/clock)*t2div
// for example a value of 30 and t2div
// of 1 the high time is 12us
// WARNING:  A value too high or low will
//           prevent the output from
//           changing.
}

}

Status
Not open for further replies.

Replies
2
Views
10K
Replies
1
Views
8K
Replies
1
Views
3K
Replies
14
Views
11K
Replies
0
Views
1K