C Example: PWM Motor Control

From Mech
Revision as of 14:53, 25 June 2007 by LIMS (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Code

Program to run a motor at different speeds using pulse width modulation (PWM), controlled by a push button.

First include header file with definitions for specific PIC. Set fuses. HS is type of external clock, low voltage protection (LVP) is off, and the watchdog timer (WDT) is off. External clock frequency of 20 MHz is specified.

  #include <18F4520.h>
  #fuses HS,NOWDT,NOPROTECT,NOLVP
  #use delay(clock=20000000)

Define pin names to be used in the main program. See header file for currently defined pin names.

  #define BUTTON PIN_A4

Begin main body of program.

  void main() {

Setup the CCP1 pin (PIN_C2 on the 18F4520 chip) to be a PWM output. Also set the timer to be used for PWM.

     setup_ccp1(CCP_PWM);
     setup_timer_2(T2_DIV_BY_1, 255, 1);

Setup an infinite loop, using a while statement.

     while( TRUE ) {

Check whether button is pressed or not, and vary duty cycle of PWM accordingly. Note that duty cycle is defined from 0-255 with 0 being 0% and 255 being 100% (8-bit number).

        if (input(BUTTON)){
           set_pwm1_duty(235);}
        else {
           set_pwm1_duty(135);}
    }
  }

Associated Circuitry