Following is an assembly program written for ATmega 2560 microcontroller to reverse a string using the stack.
.equ string_length = 12
.def zero = r17
.dseg
.org 0x380
reversed_string:
.byte string_length+1
xvar:
.byte 1
.cseg
.org 0x0000
jmp main
.org 0x0072
string:
.db "ha ha ha ha!",0
main:
;init stack pointer
ldi yl,low(0x1811)
ldi yh,high(0x1811)
out spl,yl
out sph,yh
;set xvar
ldi zl,low(xvar)
ldi zh,high(xvar)
ldi r16, -1
st z, r16
;string address in program mem
ldi zl,low(string<<1)
ldi zh,high(string<<1)
;init
clr xl
clr xh
clr zero
;loop for reading from program mem and pushing
loop:
lpm r16,z+
cpi r16,0
breq storeback
push r16
adiw xh:xl,1
rjmp loop
;loop for popping and storing to data mem
storeback:
ldi zl, low(reversed_string)
ldi zh, high(reversed_string)
loop2:
pop r16
st z+,r16
subi xl,1
sbc xh,zero
cp xl,zero
cpc xh,zero
breq end
rjmp loop2
;store nullchar
end:
st z+,zero
halt:
rjmp halt
What is maximum length of the string (string_length in the program) that can be reversed, without the stack overwriting the memory location of xvar?