;13PWM-V1.ASM
;WWW.MWFTR.COM/book.html
;Charles Kim
;This program uses CCP1 module with TMR2 for
;PWM signal generation at ccp1 (RC2) pin
;
; PWM with 2KHz 50% duty cycle 
; 
;
        list P = 16F877

STATUS		EQU	0x03
INTCON		EQU	0x0b
TMR2		EQU	0x11
PIE1		EQU	0x8c
PIR1		EQU	0x0c
PR2		EQU	0x92		;
CCP1CON		EQU	0x17
CCPR1L		EQU	0x15
T2CON		EQU	0x12
TRISC		EQU	0x87
B5		EQU	0x05
B4		EQU	0x04
PWM1		EQU	0x02
TMR2IF		EQU	0x01

	CBLOCK 	0x20   		; RAM AREA for USE at address 20h
		FIFTY
		TWENTY
		Kount120us   ;Delay count (number of instr cycles for delay)
		Kount100us
		Kount1ms
		Kount10ms
		Kount1s
		Kount10s
		Kount1m
        ENDC			;end of ram block
;
;
;The Next 5 lines must be here
;because of bootloader arrangement
;Bootloader first execute the first 4 addresses
;then jump to the address what the execution directs 
;=========================================================
        org 	0x0000      	;line 1
	GOTO	START		;line 2 ($0000)
	NOP			;line 3 ($0001)
	NOP			;line 4 ($0002)
	NOP			;line 5 ($0003)
;======================================================
;IF
;	16F877 Clock Frequency = 20 MHz
;	Tosc = 1/[Clock Frequency]
;	PWM Period = 2000Hz = 0.0005 Sec
;	TMR2 Prescale = 16
;THEN, 
;	PR2 = (period / [4*Tosc*Prescale]) - 1 
;	    = 155
;	    = 0x9b
;-----
;IF
;	PWM Ducty Cycle = 50% of the PWM period
;        		= 0.5 *(0.0005)=0.00025
;       --->[0.00025]/[5*10^(-8)*16]=312.5 ---> 313--->0x139
;	CCPR1L       CCP1CON
;       76|5432|10  76|54|3210
;       01|0011|10    |01|  
;THEN
;	CCPR1L:CCP1CON<5:4>=(PWM Duty Cycle)/(Tosc*Prescale)=139h
;	CCPR1L = 0x4e
;	CCP1CON<5:4>=b'01'
;--
;IF
;	PWM Ducty Cycle = 20% of the PWM period
;        		= 0.2 *(0.0005)=0.0001
;       --->[0.0001]/[5*10^(-8)*16]=125 --->0x7D
;	CCPR1L      CCP1CON
;       76|5432|10  76|54|3210
;       00|0111|11    |01|   
;THEN
;	CCPR1L:CCP1CON<5:4>=(PWM Duty Cycle)/(Tosc*Prescale)=7dh
;	CCPR1L = 0x1f
;	CCP1CON<5:4>=b'01'
;
;
START	
	banksel	PIE1
	clrf	PIE1
	banksel	CCP1CON
	clrf	CCP1CON
	clrf	TMR2
	clrf	INTCON
	clrf	PIR1
	movlw	0x4e		;50% Duty Cycle
	movwf	FIFTY
	movlw	0x1f		;20% Duty Cycle
	movwf	TWENTY
; PWM Period Setting
	banksel	PR2
	movlw	0x9b		;2000Hz Period
	movwf	PR2
	banksel	FIFTY
;PWM Duty Cycle
;50% is selected for 5 seconds
	movf	FIFTY, 0	;Move 50% Duty Data to W reg.
	
;For 20 % Duty
;	movf	TWENTY, 0
;
	movwf	CCPR1L
	bcf	CCP1CON, B5
	bsf	CCP1CON, B4
;TRISC Setting for output
	banksel	TRISC
	bcf	TRISC, PWM1
	banksel	T2CON
;TMR2 Prescale selection and TMR2 Turn On
	movlw	0x07
	movwf	T2CON
;CCP1CON Module Setting
;
	banksel	CCP1CON		;PWM Turn ON
	bsf	CCP1CON, 0x03	;11xx<3:0> is PWM mode
	bsf	CCP1CON, 0x02


        END

