The following example programs are available to demonstrate the basic principles for using the PWM module on the PIC18F4620 to possibly drive DC Motors, Lamps etc. at analog output voltages:

 ex1_pwm_led_simple.c

Example program that uses the PWM1 output to set the brightness of an LED to 12.5% duty cycle ((12.5% high pulse and 87.5% low pulse). An arbitrary PWM frequency of 25Khz was selected for this example to simplify the calculations.

 ex2_pwm_led_sw.c

Example program that uses the PWM1 output to change the brightness of an LED according to the input from 8 switches.  Sometimes a lower PWM frequency is required to control motors, lamps, etc.  So for this example we chose a PWM frequency of 4Khz.  The switches will be used as follows to set the duty cycle of the LED:

All switches OFF ->   0%

SW0 = ON         ->   12.5%

SW1 = ON         ->   25%

SW2 = ON         ->   37.5%

SW3 = ON         ->   50%

SW4 = ON         ->   62.5%

SW5 = ON         ->   75%

SW6 = ON         ->   87.5%

SW7 = ON         ->   100%

(As you can see it will be in 12.5% increments)

SW0 has the lowest priority and SW7 has the highest, i.e. if SW0 and SW3 is both ON, SW3 will take priority.

 ex3_pwm_led_analog.c

Example program that uses the PWM1 output to change the brightness of an LED according to the input from an analog input.  We chose a PWM frequency of 4Khz.  The brightness of the LED will be based on the following scaling of the input value:

ANALOG VAL  Duty Cycle %   SetDCPWM1 value

==========  ============   ===============

1023        100%           624 (see ex_pwm_led_sw.c to see how 624 was calcualted to be 100% duty cycle for a 4Khz PWM signal)

.

.

512         50%            312

.

.

0           0              0