;**************************************************************************
;Name:		Output Compare
;Author:	Gregory Reeves
;Date:		April 14, 2005
;Function:	Generates a 75% duty cycle,
;		3100Hz square wave.
;**************************************************************************

	ORG $2000

	JMP MAIN

TCTL1	EQU $1020	;equating memory locations
TMSK1	EQU $1022
TFLG1	EQU $1023
TCNT	EQU $100E
TOC2	EQU $1018
TOC2IV	EQU $00DC
On_cnts	RMB 2
Off_cnts RMB 2
Tot_cnts RMB 2
PORTA  	EQU $1000
ADCTL	EQU $1030
ADR4	EQU $1034
percent	RMB 2

MAIN	SEI

	LDAA #$7E	;loads jump in the output capture interrupt vector
	STAA TOC2IV

	LDD #TOCINT
	STD TOC2IV+1

	LDD #40000	;storing total count value
	STD Tot_cnts

	LDD #00		;count value needed for ontime
	STD On_cnts

	LDD #40000	;count value needed for offtime
	STD Off_cnts

	LDD TCNT	;sets the first time of TOC2
	ADDD On_cnts
	STD TOC2

	LDAA #$40	;intializing the registers
	STAA TFLG1
	STAA TMSK1
	STAA TCTL1

	CLI		;turning on the interrupts

LOOP:	JSR ADCON	;do conversions and percentage calculations
	JSR CALC
	BRA LOOP

;*************************************************************************
;Name:		TOCINT - TIMER OUTPUT CAPTURE INTERRUPT
;Author:	Gregory Reeves
;Date:		April 14, 2005
;Function:	Clears the flag and sets the time for the next
;		interrupt to occur
;*************************************************************************
TOCINT 	LDAA #$40	;clearing the OC2F bit
	STAA TFLG1

	LDAA PORTA	;check oc2 pin for on or off state
	ANDA #$40
	BNE ADDON

	LDD TOC2	;sets up for the off time sequence
	ADDD Off_cnts
	STD TOC2
	BRA EXIT

ADDON	LDD TOC2	;sets up for the next ontime sequence
	ADDD On_cnts
	STD TOC2

EXIT 	RTI		;return from the interrupt

;**************************************************************************
;Name:		ADCON - a to d conversion
;Author:	Gregory Reeves
;Date:		April 14, 2005
;Function:	Reads the value from PE1 continuously and does the
;		A/D conversion.
;**************************************************************************
ADCON	LDAA #$01	;sets adctl to the desired value
	STAA ADCTL

CVNC	LDAA ADCTL	;loops until the conversion is complete
	ANDA #$80
	BEQ CVNC

	RTS		;return from the subroutine
;**************************************************************************
;Name:		CALC - calculations for PWM
;Author:	Gregory Reeves
;Date:		April 14, 2005
;Function:	Calculates on and off counts for the
;		Pulse Width Modulation.
;**************************************************************************
CALC	LDAA ADR4	;Calculate the percentage of duty cycle
	LDAB #100
	MUL
	LDX #255
	IDIV
	STX percent

	LDAA percent+1	;Calculates the on counts
	LDAB Tot_cnts
	MUL
	STD On_cnts

	LDD Tot_cnts	;Calculates the off counts
	SUBD On_cnts
	STD Off_cnts

	RTS		;Return from subroutine

