Testing CCSInfo PicC Code Testing Pic code to communicate with PC using RS232
2007 19 Nov

Now that my lab tools are all set I need to test my Pic16F628A to get a PWM signal. This signal will later be applied to the H-Bridge circuit that will control DC motors power. For the test I’ve used this circuit:

Pic16F628A PWM Test

For the XSC1 I’ve connected my Velleman Instruments Digital Oscilloscope PCS500.

I’ve used the following code:

  1. #include <16F628A.h>
  2. #use delay(clock=4000000)
  3. #fuses NOWDT, HS, PUT, NOPROTECT, BROWNOUT, MCLR, NOLVP, NOCPD
  4. //————————————————————————————————————————————————————————————
  5. // PWM signal to be generated on pin9 -> RB3/CCP1
  6. //————————————————————————————————————————————————————————————
  7. void main(void)
  8. {
  9.  // Value = 0 Duty-Cycle (pulse width) = 0
  10.  // Value = 64 Duty-Cycle (pulse width) = 50%
  11.  // Value = 128 Duty-Cycle (pulse width) = 100% -> DC Signal
  12.  int8 value = 0; delay_ms(100); // power up delay
  13.  
  14.  // will hang on debug but necessary to turn of comparators
  15.  setup_comparator(NC_NC_NC_NC);
  16.  setup_vref(FALSE); // turn of ADC channels
  17.  set_tris_b(0b11110000);
  18.  setup_ccp1(CCP_PWM);   // Configure CCP1 as a PWM
  19.  //     (1/clock_freq)*4*Divider*128 = cycle time
  20.  //     (1/4000000)*4*16*128= 2.048 ms or 488.281 Hz
  21.  setup_timer_2(T2_DIV_BY_16, 127, 1);
  22.  
  23.  while( TRUE )
  24.  {
  25.   set_pwm1_duty(value);
  26.   // only for debug - will blink led every 0.5 second
  27.   // and increment Duty Cycle every second
  28.   output_low(PIN_B0);
  29.   delay_ms(500);
  30.   output_high(PIN_B0);
  31.   delay_ms(500);
  32.   value = value + 1;
  33.  }
  34. }
  35. //————————————————————————————————————————————————————————————

This code will generate a 2.048 ms square wave (488.281 Hz) with adjustable Duty-Cycle (pulse width) from 0% to 100%.(DC)

Leave a Reply