
	org	100h
	bra	main
Monitor 	EQU	0FF7Ch;
CmdReg		EQU	8800h;
PortA		EQU	1000h;
StatusReg	EQU	8800h
DataReg		EQU	8000h
RecBuff:	DS	19t; Define space for largest token
RecFlag:	DS 	1h;   Define flag

main:
	bsr	Config8251A;	Configure USART
	bsr	InstallInterruptVector;
	clr	RecFlag		;clears flags
	cli			;Enables Interrupt system

        ldx     #RecFlag

WaitLoop:
	brclr	0,x,0Fh,WaitLoop	;branch if flag clear
	jmp	Monitor;	End program


;Name:		Config8251A
;Input:		None
;Output: 	None
;Destroys:	A
;Description:	Configure 8251 for :
;		Asyncronous serial data
;		Baud Rate Factor = 16
;		8Bit data, no parity
;		1 stop bit
;		Enable transmitter

Config8251A:
	ldaa	#0FFh;		Sets pin 6 high
	staa	PortA;		sends hardware reset to USART
	ldaa	#00h;
	staa	PortA;
	ldaa 	#4Eh;		Load data
	staa 	CmdReg;		Send data to register
        ldaa    #05h;
	staa	CmdReg;		Transmit data
	rts;


;Name:		TransmitA
;Input:		A = the Byte to transmit.
;Output:	None.
;Destroys:	None.
;Description:	Wait until the transmitter is ready (wait until the 
;		TxRDY bit in the same Status Register is 1), then 
;		write the contents of A to the Data register.
TransmitA:
	ldx 	#StatusReg
	brclr	0,x,01h,TransmitA	; go to write A if contents
					; Back to loop to wait
	staa	DataReg			; Write data
	rts				; Return to loop for more data


;Name:		IntrRoutine
;Input:		None
;Output:	None
;Destroys:	Nothing
;Desc:		Receive one byte

IntrRoutine:
	clr	RecFlag		;Reset Flag
	bsr	Receive		;read first byte
	cmpa	#0AAh		;see if it's AA
	bne	done		;if not, bad token:discarded
	ldx	#RecBuff	;Initialize x w/buffer
	bsr	Receive		;read second byte

	cmpa	#0FFh		;if not see if free token
	bne	done		;if not, token invalad
	
	bsr 	Receive		;Token is free?
	cmpa 	#0AAh		
	bne	done		;if not token is invalid
	ldaa	#0FFh		;if so, set free token flag
	staa	RecFlag
done:
	rti

;Name:		InstallInterruptVector
;Input:		None
;Output:	None
;Destroys:	A, B, Flags
;Desc:		enables interrupt system

InstallInterruptVector:
	ldaa	#7Eh		;writes jmp
	staa	00EEh		;to memory
	ldd	#IntrRoutine	;writes value of IntrRoutine
	std	00EFh		;to memory
	rts


;Name:		Receive
;Input:		None.
;Output:	A = the Byte that was received.
;Destroys:	A, X
;Description:	Wait until the receiver has a byte (wait until the 
;		RxRDY bit in the same Status Register is 1), then 
;		read the byte from the Data register and return
;		from the subroutine with teh data in Accumulator A.

Receive:
	ldx 	#StatusReg
	brclr 	0,x,02h,Receive		;exit loop if RxRDY
	ldaa	DataReg
	rts