;%ex5a_2400 (v.16)
;*********************** version 16***********************
;remember to set /flash/linker/use memory layout from target dialog, otherwise it will not run
;and stack_pointer SP (r13) will not be set correctly.
;*******************************************************************
;ex5_2400 exercises for chapter 5 of  CENG2400. It is for your own revision purpose,no need to submit answers to tutors.
;1) create a project based on this .s code
;2) In keil-ide, use project/rebuild all target files to build the project
;3) use Debug / run_to_cursor_line to run the top line of the program, 
;4) In Debug mode/view/memory_windows,use the single step mode to 
;    view the changes of memory locations( from 0x4000041c), 
;    registers after the execution of each statement.
;5) Answer the questions and explain the observations and results.
;Note: top of stack is at 0x40000428	in lpc213x systems.
;This exercise demonstrates how stack is used in subroutine call to preserved registers contents

; declare variables	  New test12D
		AREA	|.data|, DATA, READWRITE
Data1p 	DCD 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
		align
;-------------------------------------------------------------

; User Initial Stack & Heap
        AREA    |.text|, CODE, READONLY

        EXPORT  __main
__main	;
loop1	;	
		MOV r0, #1	;save 1 into r0
		MOV r1, #2	;save 2 into r1
		MOV r2, #3	;save 3 into r2
;question1:what is the value in r13 now?
		BL 	subroutine
;question5:what is the value in r0 now?
		NOP
		B loop1
										  

subroutine    STMED r13!, {r0-r2,r14} ;save r0,r1,r2,r14 in  stack

;question2:what is the value in r13 now and why?
;saved in stack
; and r13-decremented 4x4=16=0x10 times , so 0x40000428-0x10=0x40000418
;r13-
;question3:what are stored in the stack ?
			  MOV r0,#4	 	;save 4 into r0
			  MOV r1,#5		;save 5 into r1
			  MOV r2,#6		;save 6 into r2
			  LDMED r13!,{r0-r2,r14}  ;get back r0,r1,r2,r14 from stack
;question4:what is the value in r13 now?
			  BX LR

		END