/* 
 * ParamPassing1c.asm
 *   Modified: 6 Feb 2024
 *   Authors:  Dr. Schwartz, Josh Weaver
 *   Purpose: Demonstrate passing of parameter address (a pointer to data memory)
 *            to a subroutine using registers
 */ 
.include "ATxmega128A1Udef.inc"
;******************************INITIALIZATIONS***************************************
.equ	stack_init = 0x3FFF ; Initialize stack pointer (between 0x2000 & 0x3FFF)	
                            ; Default is 0x3FFF
.org 0x0000
	jmp MAIN
.dseg
.org 0x2000                 ; Place Data at address 0x2000
DATA: .byte 2               ; Define space for data in data memory
;*******************************PROGRAM START****************************************
.CSEG
.org 0x200
MAIN:
    ldi r16, low(stack_init)
    out CPU_SPL, r16	        ; Initialize low byte of stack pointer
    ldi r16, high(stack_init)
    out CPU_SPH, r16	        ; Initialize high byte of stack pointer
		
	
 	ldi r16, 0x37           ; Load a number into first byte of data memory 
	sts DATA, r16			;   (at DATA)
 	ldi r16, 0xA3           ; Load a number into second byte of data memory 
	sts DATA+1, r16			;   (at DATA+1)
	ldi XL, low(DATA)
	ldi XH, high(DATA)

;	ldi r16, 0x37           ; Load a number into first byte of data memory 
;	st	X+, r16             ;   (at Data)
;	ldi r16, 0xA3           ; Load a number into second byte of data memory
;	st	X, r16              ;   (at Data+1)
;	ld	r16, -X             ; Restore X to point to DATA (TRICK to do DEC_X)
	
    rcall AVG               ; Call subroutine AVG to get the average
HERE:	
    rjmp HERE
;********************************SUBROUTINES*****************************************
/************************************************************************************
 * Name:     AVG
 * Purpose:  Get the Average of two data bytes in successive memory locations in
 *           data memory pointed to by X
 * Inputs:   X is the pointer to data memory location of Data			 
 * Output:   r16 is the place for the result
 * Affected: r16, r17, X
 ***********************************************************************************/
AVG:
    ld r16, X+     ; Load r16 with first point in program memory and increment Z
    ld r17, X      ; Load r17 with the second point in program memory
    add r16, r17    ; r16 = r16 + r17
    asr r16         ; Shift A right by 1 bit (divide by 2) keeping bit 7
                    ; (for sign extension) 
    ret	            ; Return from subroutine