simple PWM – DSPIC30F2010

Photo of author

By Jackson Taylor

100KHz AND 200KHz SQUARE WAVE USING DSPIC


PROGRAM
program BLINK
dim current_duty, current_duty1, pwm_period1 , pwm_period2  as word
main:
  PORTD = 0                                  ‘ set PORTD to 0
  TRISD = 0                                  ‘ designate PORTD pins as output
  current_duty  = 20                        ‘ initial value for current_duty
  current_duty1 = 10                        ‘ initial value for current_duty1
 pwm_period1 = PWM_Init(100000 , 1, 1, 2)   ‘frequency ,channel no.,timer prescale value(1, 8, 64, and 256 ) ,timer no (2 or 3)
  pwm_period2 = PWM_Init(200000, 2, 1, 3)    ‘frequency ,channel no.,timer prescale value(1, 8, 64, and 256 ) ,timer no (2 or 3)
  PWM_Start(1)
  PWM_Start(2)
  PWM_Set_Duty(current_duty,  1)             ‘ Set current duty for PWM1
  PWM_Set_Duty(current_duty1, 2)             ‘ Set current duty for PWM2              ‘OC2RS=50—duty cycle actuall writes to this register
  while (TRUE)                               ‘ endless loop
  wend
end.
HOW TO CALCULATE PWM DUTY CYCLE

  • PWM duty ratio depend on output frequency
  • 16MHz  crystal as clock source
  • PRESCALE VALUE ARE  1, 8, 64, and 256

Maximum duty ratio = FOSC  /(FOUTPUT  * 4  * PRESCALE VALUE)  -1
FOR 100KHz
Maximum duty ratio = 16MHz / (100KHz *4 *1)  – 1=39
FOR 200KHz
Maximum duty ratio = 16MHz / (200KHz *4 *1)  – 1=19
I HAVE USED 50% DUTY RATIO FOR BOTH
800KHz SQUARE WAVE USING DSPIC



program BLINK
dim current_duty, current_duty1, pwm_period1 , pwm_period2  as word
main:
  PORTD = 0                                  ‘ set PORTD to 0
  TRISD = 0                                  ‘ designate PORTD pins as output
  current_duty  = 20                        ‘ initial value for current_duty
  current_duty1 = 2                        ‘ initial value for current_duty1
 pwm_period1 = PWM_Init(100000 , 1, 1, 2)   ‘frequency ,channel no.,timer prescale value(1, 8, 64, and 256 ) ,timer no (2 or 3)
  pwm_period2 = PWM_Init(800000, 2, 1, 3)    ‘frequency ,channel no.,timer prescale value(1, 8, 64, and 256 ) ,timer no (2 or 3)
  PWM_Start(1)
  PWM_Start(2)
  PWM_Set_Duty(current_duty,  1)             ‘ Set current duty for PWM1
  PWM_Set_Duty(current_duty1, 2)             ‘ Set current duty for PWM2              ‘OC2RS=50—duty cycle actuall writes to this register
  while (TRUE)                               ‘ endless loop
  wend
end.