; ************************************
; * UART Communication 3  by PEK '2000 
; *
; * Send a sequence of bytes with use
; * of Receive interrupt routine.
; * When a specific command comes on
; * RxD line the program send a
; * sequences of data back on TxD.
; * The program have the same function
; * that UART_EX2 but in a different
; * way.
; *
; * 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


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,0x98
	out	UCR,temp		; Rx 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_send:
	lpm				; Get Constant from Flash, R0=(Z)
	mov	numb_b,R0		; Number of bytes to send in numb_b
rx_send_loop:
	sbis	USR,UDRE		; Loop if transmit not complete
	rjmp	rx_send_loop
	adiw	ZL,1			; Point to byte
	lpm
	out	UDR,R0			; Send next byte in the sequence
	dec	numb_b
	brne	rx_send_loop		; Is all bytes transfered ?
	reti

Send_Data1:
	ldi	ZH,high(data1*2)	; Z points to data1
	ldi	ZL,low(data1*2)
	rjmp	rx_send

Send_Data2:
	ldi	ZH,high(data2*2)	; Z points to data2
	ldi	ZL,low(data2*2)
	rjmp	rx_send


; ************************************
; * 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
