	org $2000
	jmp main

porta 	equ $1000
PACTL	equ $1026
tcnt 	equ $100E
tflg1	equ $1023
tmsk1 	equ $1022
tic2	equ $1012
tctl2	equ $1021
out2bsp equ $ffc1
outcrlf equ $ffc4

Sonar_start	rmb 2
Sonar_end 	rmb 2
Sonar_ans	rmb 2	
main:	

Sonar:	

; add after testing (phase 1) is completed
;
;	psha
;	pshb
;	pshx


	ldx #pactl	; Set PA7 for OUTPUT
	bset 0,x #$80
	ldx #porta	; Trigger on PA7 set high - Trigger pulse
	bset 0,x #$80
	ldd tcnt	; capture present time
	std Sonar_start	
	ldx #porta	; turn off trigger pulse
	bclr 0,x #$80


	ldx #tctl2
	bset 0,x #$08
	bclr 0,x #$04	;capture falling edge of PA1 (IC2)	

	ldaa #$02	;clear flag for IC2
	staa tflg1
	
sonar_l2:
	ldaa tflg1	;wait for flag to go high
	anda #$02
	beq sonar_l2

	ldd tic2	;get time of falling edge and store
	std Sonar_end

	ldd Sonar_end		;calculate time
	subd Sonar_start
	std Sonar_ans

; remove after testing is complete
	ldx #Sonar_ans	;print time ticks in hex to screen
	jsr out2bsp
	jsr outcrlf
	
	jmp Sonar
;----------------------------------------------------------

	
	pulx
	pulb
	pula

	rts