; 16F818 PWM example code
;
; Device 16F818
list p=16F818 ; list directive to define processor
#include <p16F818.inc> ; processor specific variable definitions
errorlevel -302, -207
__config H'3F10'
cblock 0x20 ;start of general purpose registers
count ;used in delay routine
count1 ;used in delay routine
counta ;used in delay routine
countb ;used in delay routine
temp ;temp storage
;rate ;adc value
endc
Fwd1 equ 0x00 ;pin for left motor reverse
Rev1 equ 0x01 ;pin for left motor forward
;pins 1 and 2 are the 1 PWM channel
org 0x0000
nop ;for bootloader compatibility
nop
nop
goto START
org 0x0010
START call Initialise
MainLoop:
movlw d'64'
call Speed
call Long_Delay
movlw d'192'
call Speed
call Long_Delay
movlw d'10'
call Speed
call Long_Delay
movlw d'228'
call Speed
call Long_Delay
goto MainLoop
Initialise:
banksel OSCCON
movlw b'01100000' ;uae1
movwf OSCCON
banksel ADCON1 ;turn off A2D
movlw 0x0E; AN0 analog, rest digital, left justified [255]
movwf ADCON1
banksel PORTA
banksel TRISB
movlw 0 ;set PORTB as all outputs
movwf TRISB
banksel PORTB
movf CCP1CON,W ;set CCP1 as PWM
andlw 0xF0
iorlw 0x0C
movwf CCP1CON
movlw .126 ;set highest PWM value
banksel PR2 ;over this (127) is permanently on
movwf PR2
banksel TMR2
movf T2CON,W ;set prescaler to 4;;;16
andlw 0xF8 ;PWM at 2500HZ
iorlw 0x01;;;2
movwf T2CON
movf T2CON,W ;set postscaler to 1
andlw 0x07
iorlw 0x00
movwf T2CON
clrf CCPR1L ;set PWM to zero
bsf T2CON,TMR2ON ;and start the timer running
return
Speed: ;use value in W to set speed (0-127)
movwf temp
btfsc temp,7 ;if more than 128 set speed in reverse
call ReverseMtr ;so '1' is very slow forward
btfss temp,7 ;and '129' is very slow reverse
call ForwardMtr
andlw 0x7F
movwf CCPR1L
return
ReverseMtr:
bsf PORTB,Rev1 ;set pins for reverse
bcf PORTB,Fwd1
return
ForwardMtr:
bcf PORTB,Rev1 ;set pins for forward
bsf PORTB,Fwd1
return
;Delay routines
Long_Delay
return
movlw .50 ;delay 5 seconds
call Delay100W
return
Delay100W movwf count ;delay W x 100mS
d2 call Delay100 ;maximum delay 25.5 seconds
decfsz count ,f
goto d2
return
Delay255 movlw 0xff ;delay 255 mS
goto d0
Delay100 movlw .100 ;delay 100mS
goto d0
Delay50 movlw .50 ;delay 50mS
goto d0
Delay20 movlw .20 ;delay 20mS
goto d0
Delay10 movlw .10 ;delay 10mS
goto d0
Delay1 movlw .1 ;delay 1mS
goto d0
Delay5 movlw 0x05 ;delay 5.000 ms (4 MHz clock)
d0 movwf count1
d1 movlw 0xE7
movwf counta
movlw 0x04
movwf countb
Delay_0 decfsz counta, f
goto $+2
decfsz countb, f
goto Delay_0
decfsz count1 ,f
goto d1
return
;end of Delay routines
end