Download the module: PWM2.bas
Other programs that use this module:
Variable Frequency PWM Example
The SetFreqByTable() function uses a constants table of PR2 and Timer2 Prescaler load values so the user can switch easily between optimum frequencies and duty cycle resolution. A small utility program has been created to simplify the creation of this array of constants which can be downloaded from HERE. A screenshot of this utility is provided below.

Here is example code that uses some of the newly added functions. This example uses an 18F2550 @ 48MHz. Potentiometers are connected to AN2 and AN3 which create the variable duty-cycle for PWM1 and PWM2 outputs. A pushbutton connected to GND and PORTB.0 is used to toggle between PWM frequencies of 11.75KHz and 5.8KHz which have resolutions of 1024 and 512, respectively. These frequencies were determined from a constants table created with the PWM_Writer Utility. The EasyPIC3 PIC development board was used for this test.
Device = 18F2550 Clock = 48 ' set up config for 8MHz crystal and USB Config USBDIV = 2 Config CPUDIV = OSC1_PLL2 Config PLLDIV = 2 Config FOSC = HSPLL_HS Include "pwm2.bas" Include "adc.bas" Dim adc0,adc1 As Word Dim tt As Byte TRISA = 15 TRISB = 1 tt = 0 ADCON1 = 11 // AN0..AN3 active ADC's INTCON2.7 = 0 // RBPU active PWM.SetFreqByTable(tt) PWM.Start1 PWM.Start2 While true adc0 = ADC.Read(2) adc1 = ADC.Read(3) If tt = 0 Then PWM.SetDuty1(adc0) PWM.SetDuty2(adc1) Else PWM.SetDuty1(adc0 >> 1) PWM.SetDuty2(adc1 >> 1) End If If (PORTB And 1) = 0 Then Inc(tt) tt = tt And 1 PWM.SetFreqByTable(tt) Repeat DelayMS(5) Until (PORTB And 1) 0 EndIf Wend
Link: What is a Swordfish Library?