Here is the code that I am basically going to use. I tested one port only. Plan to run the code as is then add other ports etc but only have 3 ports with dimming capabilities using the 18f2221 many thanks to Tumbleweed
// Swordfish BASIC three-channel software PWM using TMR2 and ADC inputs
Device = 18F4520
Clock = 32
Include "intosc.bas"
// do NOT include setdigitalio
// to use PORTB for the ADC all pins must be in analog mode due to the way
// these old pics map ADC inputs
Dim test As PORTE.0
Dim z As Byte
Include "adc.bas"
Dim x As Byte
// ADC pot inputs
// used to set the PWM duty cycle for PWM1-PWM3
// connect pot upper lug = VDD, lower lug = GND, wiper = port IO
Dim
POT1 As PORTB.0, // RB0/AN12
POT2 As PORTB.1, // RB1/AN10
POT3 As PORTB.2 // RB2/AN8
// ADC channels
Const
CH_POT1 = 12, // AN12
CH_POT2 = 10, // AN10
CH_POT3 = 8 // AN8
// PWM outputs
Dim
PWM1 As PORTA.0,
PWM2 As PORTA.1,
PWM3 As PORTA.2
// pwm duty cycles (from ADC) 0=min, 255=max
Dim
pwm1_duty As Byte,
pwm2_duty As Byte,
pwm3_duty As Byte
Dim pwm_period As Byte
// pwm timer TMR2
Dim
TMR2IF As PIR1.bits(1),
TMR2IE As PIE1.bits(1),
TMR2ON As T2CON.bits(2)
// set IO pin directions and initial settings
Sub InitIO()
// set inputs
Input(POT1)
Input(POT2)
Input(POT3)
// set outputs (low to start)
Low(PWM1)
Low(PWM2)
Low(PWM3)
End Sub
// pwm TMR2 interrupt
Interrupt tmr2_isr()
TMR2IF = 0
pwm_period = pwm_period + 1
If (pwm_period >= pwm1_duty) Then
PWM1 = 0
Else
PWM1 = 1
EndIf
If (pwm_period >= pwm2_duty) Then
PWM2 = 1
Else
PWM2 = 0
EndIf
If (pwm_period >= pwm3_duty) Then
PWM3 = 1
Else
PWM3 = 0
EndIf
End Interrupt
main:
For z = 0 To 5
test = 1
DelayMS(500)
test = 0
DelayMS(500)
Next
InitIO()
// ADC setup
ADCON1 = $00 // all pins set to analog mode, VREF = VDD/GND
ADCON2 = ADC.FRC // ADC clock = Frc
ADC.ADFM = 0 // left justify (we only use the 8 MSB's)
ADC.SetAcqTime(100) // 100us delay
pwm_period = 0
pwm1_duty = 0
pwm2_duty = 0
pwm3_duty = 0
// setup pwm timer TMR2
// 25KHz = 40us/bit -> 40us x 256 = 10240us period, ~10ms period (100Hz)
T2CON = %00000001 // T2OUTPS<3:0>=%000 (1:1), TMR2ON=0, T2CKPS<1:0>=%01 (1:4)
PR2 = 176
TMR2 = 0
TMR2IF = 0
TMR2IE = 1
TMR2ON = 1
Enable(tmr2_isr)
While (true)
pwm1_duty = ADC.Read(CH_POT1) >> 8
pwm2_duty = ADC.Read(CH_POT2) >> 8
pwm3_duty = ADC.Read(CH_POT3) >> 8
End While