;==================================================================================================
; TEST - reading an displaying bits 6 & 7 from AY-3-8912 I/O port
;==================================================================================================

		cpu	z80undoc
		org	32768			; must be in fast RAM

START		di				; disable interrupt
		call	SET_AY_PORTS		; initialice AY-3-8912
		call	READ_AY_IOPORT
END		ei				; enable interrupt
		ret				; return to BASIC

; ZX Spectrum 128k RS232/MIDI
;	bit	manual	dir.	better name	
;	A2	CTS	output	RTS
;	A3	RxD	output	TxD
;	A6	DTR	input	CTS
;	A7	TxD	input	RxD

SET_AY_PORTS	ld	bc,65533		; select AY register 7
		ld	a,7
		out	(c),a
		ld	a,b			; A = 255 / set IO port as output (1 on bit 6) and disable all sound channels
		ld	b,191			; BC = 49149 / AY data port
		out	(c),a
		ld	b,a			; BC = 65535 / AY register port
		ld	a,14			; select AY register 14 (IO port)
		out	(c),a
		ld	a,b			; A = 255
		ld	b,191			; BC = 49149 / data port
		out	(c),a			; write data byte 255, all bits high (like pullups?)
		ret

; this code is for testing RTS pulse before reading RxD, similar to Paul Farrow code, because i need
; test how really AY-3-8912 works without very slow switching between read/write mode from datasheet

READ_AY_IOPORT	ld	c,253			; 7T	low byte of addresses 49149/65533
READ_AY_LOOP_1	ld	hl,16384		; 10T
		ld	de,4096			; 10T	size of 2/3 video ram without color attributes
		ld	b,191			; 7T	BC = 49149
		ld	a,11111011b		; 7T	bit 2 to 0 (RTS output)
		out	(c),a			; 12T
		nop				; 4T	12*4 = 48T delay
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		nop				; 4T
		ld	a,255			; 7T	it is important write 255 to IO port before reading
		out	(c),a			; 12T
		ld	b,a			; 4T	BC = 65533
; short RTS pulse 12+12*4+7 = 67T (18.9μs)
READ_AY_LOOP_2	in	a,(c)			; 12T
		ld	(hl),a			; 7T
; 		nop				; 4T	+12T delay can synchronize this code to 57600bps
; 		nop				; 4T
; 		nop				; 4T
		inc	hl			; 6T
		dec	de			; 6T
		ld	a,d			; 4T
		or	e			; 4T
		jp	nz,READ_AY_LOOP_2	; 10T
; read port every 12+7+6+6+4+4+10 = 49T (13.81μs)
		call	8020			; test BREAK
		jp	nc,END			; end if pressed
		jp	READ_AY_LOOP_1