Does this work OK?
Code:
OSCCON = $70
DEFINE OSC 8
CSET VAR WORD 'CURRENT SET
CSEN VAR WORD 'CURRENT SENCE
DUTY VAR WORD 'PWM DUTY CYCLE
O_Duty VAR WORD 'previous Duty-cycle
MinDuty CON 2 'minimum duty cycle
MaxDuty CON 40 'maximum duty cycle
ADCON0 = %00011001
ADCON1 = %00001111
ADCON2 = %10111111
TRISA = %00000000
TRISB = %00110011
Define ADC_BITS 10 ' Set number of bits in result
Define ADC_CLOCK 3 ' Set clock source (5=fosc/16)
Define ADC_SAMPLEUS 10 ' Set sampling time in uS
CSET = 0
CSEN = 0
DUTY = 20 ' duty value for 50% duty cycle
PR2 = 9 '
T2CON = %00000100 ' timer2 on, prescale 1:1
CCPR1L = DUTY>>2 ' MSB of duty cycle value
CCP1CON.4=DUTY.0 ' set PWM mode and store the
CCP1CON.5=DUTY.1 ' 2 LSB of duty
CCP1CON = %00001100
LOOP:
ADCIN 6, CSET 'READ VALUE OF CURRENT SET POT
ADCIN 4, CSEN 'READ VALUE OF CURRENT SENSE
' test for CSEN > CSET*2
IF CSEN > (CSET*2) THEN ' minimize short-cycling (increase as needed)
IF DUTY > MinDuty THEN ' don't allow below minimum duty
DUTY = DUTY - 1
ENDIF
ENDIF
IF CSEN < (CSET/2) THEN
IF DUTY < MaxDuty THEN ' don't allow greater than max duty
DUTY = DUTY + 1
ENDIF
ENDIF
IF O_Duty = DUTY THEN LOOP ' does duty-cycle need updating?
O_Duty = DUTY ' yes. copy last duty value for next comparison
CCP1CON.4=DUTY.0 ' set PWM mode and store the
CCP1CON.5=DUTY.1 ' 2 LSB of duty
CCPR1L = DUTY>>2 ' MSB of duty cycle value
GOTO LOOP
A low-pass filter on each A/D input would also help.
Bookmarks