*
* sony-ir.asm
*
* interrupt routine decodes the Sony format IR protocol
*
* by Brian Silverman				(bss@media.mit.edu)
* ported to IC and Handy Board by Fred Martin	(fredm@media.mit.edu)
* January 27, 1996
*

TIC1	EQU	$1010	; Timer Input Capture register 1
TFLG1	EQU	$1023	; main Timer interrupt Flag register 1
TCTL2	EQU	$1021	; Timer Control register 2
TMSK1	EQU	$1022	; main Timer interrupt Mask register 1

TOC4INT	EQU	$E2	; Timer Output Compare 4
TIC1INT	EQU	$EE	; Timer Input Capture 1

	org	MAIN_START


ir_timer		fcb	0
ir_shift		fcb	0
ir_phase		fcb	0
ir_data			fcb	0
ir_data_copy		fcb	0
last_captured_input	fdb	0

subroutine_initialize_module:
* poke isr vector
	ldx	#$bf00		* assume handy board's special mode
	ldd	#ir_routine
	std	TIC1INT,X

* install millisec routine
	ldd	TOC4INT,X		; SystemInt on TOC4
	std	millisec_exit+1

* install ourself as new vector
	ldd	#millisec_routine
	std	TOC4INT,X

	rts


* the millisec routine is installed into the pcode's "SystemInt" routine,
* which is called every millisecond
millisec_routine
	inc	ir_timer
	bne	millisec_exit
	dec	ir_timer
	clr	ir_data

millisec_exit
	JMP	$0000	; this value poked in by init routine


* the ir routine is called whenever a falling edge (i.e., beginning of 
* valid ir signal) is received
ir_routine
	ldaa	#4
	staa	TFLG1		* clear tic1 interrupt flag
	
	ldaa	ir_timer
	bpl	irrot20
	ldaa	#9
	staa	ir_phase
	bra	irrot80

irrot20	ldaa	ir_phase
	beq	irrot80		* inhibit repeats
	ldd	TIC1
	subd	last_captured_input
	cmpd	#3000
	ror	ir_shift
	dec	ir_phase
	bne	irrot80
	ldaa	ir_shift
	coma

irrot60	staa	ir_data
	staa	ir_data_copy

irrot80	ldd	TIC1
	std	last_captured_input
	clr	ir_timer
	rti

* returns IR value received since last call
subroutine_ir_data:
	clra
	ldab	ir_data_copy
	clr	ir_data_copy
	rts

* call with 1 to turn on; 0 to turn off
subroutine_sony_init
	ldx	#$1000
	tstb
	beq	sony_off
	bset	TMSK1,X $04	* enable tic1 interrupt
	bset	TCTL2,X $20	* on falling edges (i.e., IR detects)
	bclr	TCTL2,X $10	
	rts
sony_off
	bclr	TMSK1,X $04
	rts

