This is part of some code that I posted a long time ago in the "code examples" section of this forum.
Writing directly to the hardware registers offers much more flexibility than using the PBP HPWM command.
It was written for use with an 18F872x chip running either at 20Mhz or 40Mzh
It was written for use with HYPERTERMINAL, and recognizes the ESC codes for the VT-xxx type terminals. Once you select the PWM frequency, you can use the UP and DOWN arrows on the keyboard to change the duty cycle.
You might have to change a few things, since this is only a segment of a larger program, but it should show you what is going on.
Code:
PWMTester:
HSEROUT [13,10,10,"Test PWM ",13,10]
HSERin [Char]
HSEROUT [13,REP 10\4]
IF Char !=13 THEN
GOTO PWMTester
ENDIF
HSEROUT ["Pick PWM Frequency 1 = 312Khz,2 = 156Khz, 3 = 78Khz, 4 = 39Khz "]
HSERin [Char]
IF Char < "1" or Char > "4" THEN
HSEROUT [13,10,10]
GOTO PWMTester
ENDIF
IF Mhz40 = 1 THEN ; Set MHz = 1 if running 40 Mhz, to "0" if running 20Mhz
Select CASE Char
CASE "1"
PWMFREQ = $1F
NumBits = 7
MaxPWM = 127
CASE "2"
PWMFREQ = $3F
NumBits = 8
MaxPWM = 255
CASE "3"
PWMFREQ = $7F
NumBits = 9
MaxPWM = 511
CASE "4"
PWMFREQ = $FF
NumBits = 10
MaxPWM = 1023
END SELECT
ELSE
Select CASE Char
CASE "1"
PWMFREQ = $F
NumBits = 6
MaxPWM = 63
CASE "2"
PWMFREQ = $1F
NumBits = 7
MaxPWM = 127
CASE "3"
PWMFREQ = $3F
NumBits = 8
MaxPWM = 255
CASE "4"
PWMFREQ = $7F
NumBits = 9
maxPWM = 511
END SELECT
ENDIF
CCP1CON = %00001100
CCPR1L = %00010000
CCPR1H = %00000000 ' Initialize to 0, PWM register
PR2 = PWMFREQ
T2CON = %00000100 ' Prescale 1, Timer2 ON - Needed for PWM
PORTC.2 = 0
TRISC.2 = 0
PWMVal = 0
Gosub WritePWMreg
HSEROUT [13,10,10]
HSEROUT ["PWM Value (",#MaxPWM," Max)",13,10]
HSEROUT ["0",8]
NewChar:
HSERIN [Char]
If Char = 27 THEN
HSERIN 50,NoArrow,[Char2,Char3]
IF Char3 = 65 AND PWMVal < MaxPWM tHEN
PwmVal = PWMVal + 1
ENDIF
IF Char3 = 66 AND PWMVal > 0 tHEN
PwmVal = PWMVal - 1
ENDIF
HSEROUT [#PWMVal," ",REP 8\7]
GOSUB WritePWMReg
ENDIF
goto NewChar
NoArrow:
Break = 1
PWMVal = 0
Gosub WritePWMReg
CCP1CON = 0 ; Shut off the PWM controller
GOTO PWMTester
WritePWMReg:
CCPR1L = PWMVal >> 2
CCP1CON.5=PWMVal.1
CCP1CON.4=PWMVal.0
RETURN
Bookmarks