; ************************************
; * UART Communication 2  by PEK '2000 
; *
; * Send a sequence of bytes with use
; * of Send and Receive interrupt
; * routines.
; * When a specific command comes on
; * RxD line the program send a
; * sequences of data back on TxD.
; *
; * Use a 4 MHz crystal!
; ************************************


.include "8515def.inc"


; ************************************
; * Register Definitions             
; ************************************
.def	temp	=R16
.def	data	=R17
.def	numb_b	=R18			; Number of bytes left to send in a sequence


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0
	rjmp	start
.org 9	
	rjmp	rx_comp			; UART Rx Complete Handler
.org 11
	rjmp	tx_comp			; UART Tx Complete Handler


start:	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp
		
	ldi	temp,0xD8
	out	UCR,temp		; Rx INT, Tx INT, Rx Enable, Tx Enable
	ldi	temp,12
	out	UBRR,temp		; 19200 Baud (4 MHz crystal)

	sei				; Enable global interrupts
	
loop:
	rjmp	loop


; ** UART Rx Complete Handler ********
rx_comp:
	in	data,UDR		; Get data from UART Data Register

	cpi	data,0x01
	breq	Send_Data1
	cpi	data,0x02
	breq	Send_Data2
	reti

rx_quit:
	ldi	temp,0x58		; Disable Rx Complete ISR until the sequence of
	out	UCR,temp		; bytes is transfered.

	lpm				; Get Constant from Flash, R0=(Z)
	mov	numb_b,R0		; Number of bytes to send in numb_b
	adiw	ZL,1			; Point to first byte to send
	lpm
	out	UDR,R0			; Start to send the first byte in the sequence
	reti

Send_Data1:
	ldi	ZH,high(data1*2)	; Z points to data1
	ldi	ZL,low(data1*2)
	rjmp	rx_quit

Send_Data2:
	ldi	ZH,high(data2*2)	; Z points to data2
	ldi	ZL,low(data2*2)
	rjmp	rx_quit


; ** UART Tx Complete Handler ********
tx_comp:
	dec	numb_b
	breq	tx_fin			; Is all bytes transfered ?
	adiw	ZL,1			; Point to next byte to send
	lpm
	out	UDR,R0			; Send next byte in the sequence
	reti

tx_fin:
	ldi	temp,0xD8		; Enable Rx Complete ISR
	out	UCR,temp
	reti


; ************************************
; * Constant Definitions
; ************************************
.cseg
data1:	.DB	3,'A','B','C'		; 3 number of bytes to send
data2:	.DB	12,"UART Example"	; 12 number of bytes to send