/* 
 * ParamPassing4.asm
 *   Modified: 6 Feb 2024
 *   Authors:  Dr. Schwartz
 *   Purpose: Demonstrate passing of parameter address global data memory
 */ 
.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
DATA1: .byte 1              ; Define space for data in data memory
.org 0x2037
DATA2: .byte 1
;*******************************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 of data memory 
	sts DATA1, r16			;   (at DATA1)
;	ldi XL, low(DATA1)
;	ldi XH, high(DATA1)	
;	st	X, r16   

    ldi r16, 0xA3           ; Load a number into second byte of data memory
	sts DATA2, r16			;   (at DATA2)
;	ldi XL, low(DATA2)
;	ldi XH, high(DATA2)
;	st	X, r16              
	
    rcall AVG               ; Call subroutine AVG to get the average
HERE:	
    rjmp HERE
;********************************SUBROUTINES*****************************************
/************************************************************************************
 * Name:     AVG
 * Purpose:  Get the Average of two data bytes in global data memory locations 
 *           DATA1 and DATA2
 * Inputs:   DATA1 and DATA2 (global data memory locations)
 * Output:   r16 is the place for the result
 * Affected: X,r16, r17
 ***********************************************************************************/
AVG:
	lds r16, DATA1
;	ldi XL, low(DATA1)
;	ldi XH, high(DATA1)
;	ld r16, X
	lds r17, DATA2
;	ldi XL, low(DATA2)
;	ldi XH, high(DATA2)
;	ld r17, X

    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
