;************************************************************************
;		    Filename: INTRRPT.ASM
;		 Description: Interrupt service routine.
;************************************************************************

;- Desired to have high resolution counters for debounce and other counters therefore set the
;  interrupt rate as fast as possible.

;- Desired to give the processor maximum time to allow for regular program execution
;  without being bogged down by frequent interrupt servicing, threfore set the interrupt
;  rate as slow as possible.

;- The fastest counter is the debounce counter at least 10ms intervals. The resolution of
;  this counter is not important as long as the keys get debounced properly.

;			    uP clock = 32,768 Hz
;	     Instruction clock= uP/4 =  8,192 Hz
;   Prescaler set to 1 (divide by 2) =  4,096 Hz
;Interrupt from Timer rollover (256) =     16 Hz (62.5ms)


	;Save contents of various registers	
	movwf	temp_w		;save w contents
	swapf	STATUS,w	;swap status, result in W
	movwf	temp_s		;save status contents (swapped)


	BCF	INTCON,T0IF	;Clear the interrupt flag

	BTFSC	SEMAPHORE,0	;check if short beep was played
	CLRF	PORTA		;short beep was played so shut beeper off 
	
	BCF	SEMAPHORE,0	;Stop short beep after 1/16 sedond (1 interrupt)	

;************************************************************************************
;Increment 1Hz counter also rollover to MINUTE counter

	DECF	PRECOUNT,f	;Count for one second
	BTFSS	STATUS,Z
	GOTO	INT_END		;Skip incrementing if one second has not passed yet	

	;One second has passed
	

	BSF	SEMAPHORE,0	;Short BEEP every second
	BSF	PORTA,0		;preset beeper voltage
	BCF	PORTA,1		;preset beeper voltage
	
	BCF	SEMAPHORE,1	;Remove long beep request

	
	MOVLW	INTSPERSEC	;Preset the precounter again
	MOVWF	PRECOUNT

	INCF	SECONDS
,f
	MOVF	SECONDS,W
	MOVWF	PORTB
	
	;Check that 33 seconds has elapsed for one leg

	;Leg count

	SUBLW	D'33'		;W,C=33-SECONDS
	BTFSC	STATUS,C	;Branch if SECONDS > 33
	GOTO	INT_END		;SECONDS must have been less < 33
	
	CLRF	SECONDS		;reset the SECONDS counter to 0
	DECF	LEGCTR,f	;Decrement LEG counter

	BCF	SEMAPHORE,0	;unrequest short beep	
	BSF	SEMAPHORE,1	;request long beep
	BSF	PORTA,0		;preset beeper voltage
	BCF	PORTA,1		;preset beeper voltage
	
	MOVF	LEGCTR,w	;check if leg counts are complete
	BTFSS	STATUS,Z	;Z=set if LEGCTR is done (0)
	GOTO	INT_END		;Leg counts are not complete yet.
	

	BSF	SEMAPHORE,2	;request to go to sleep



;************************************************************************************


INT_END
	;Restore the saved registers
	swapf	temp_s,w	;reswap status, result in W
	movwf	STATUS		;restore status
	swapf	temp_w,f	;swap, back in file
	swapf	temp_w,w	;reswap in W
	RETFIE

;************************************************************************************



