This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Recursive Fibonacci sequence on M4 - improving the code

Hello,

I'm learning assembly on the ARM Cortex M4. I'm trying to write a code which will display the first 5 Fibonacci numbers in register R3 then go into an endless loop.

This would be the C code I'm trying to emulate:

int fibbonacci(int n) {
   if(n == 0){
      return 0;
   } else if(n == 1) {
      return 1;
   } else {
      return (fibbonacci(n-1) + fibbonacci(n-2));
   }
}

I wrote the following assembly code in Keil:

;Recursive implementation - Print fibonacci sequence for first 5 numbers in R3 
; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
; R4 = counter
__main
        MOV     R0, #4
		;MOV	R4, #3
Sum     
        CMP     R0, #1
        BEQ     done
        SUBS    R0, R0, #1
        BL      Sum
		;SUBS	R4, #1
		;CMP		R4, #0
		;BEQ 	Stop
        POP     {R1, R2}
        ADD     R0, R1, R2
        MOV     R3, R0
        PUSH    {R0, R1}
        BX      LR
        
Stop    B       Stop
        
        
done
        MOV     R0, #0
        MOV     R3, R0
        PUSH    {R0}
        
        MOV     R0, #1
        MOV     R3, R0
        PUSH    {R0}
        
        BX      LR
        ALIGN
		END

Problem is that I was not able to make the code branch to the Stop loop after the first 4 numbers are displayed into the register R3. What happens is when I reach the 'BX LR' instruction in the 'Sum' subroutine the code keeps branching to the Sum and keeps on printing Fibonacci numbers forever. I could somehow make use of the R4 register to decrement it few times so when we have 4 numbers displayed in register R3 we branch to the stop loop but that is not a very elegant solution.

I just want the number of numbers to be printed in the register R0 and then once the first 4 numbers are displayed into R3 the code should return from the Sum(4) and go to the stop loop below.
I know I have to somehow make use of the LR register to achieve this but I was not able to figure it out. 
Can you please help me by helping me figure out how I could modify this code so that I can achieve what I want? Thank you for reading and sorry for my English I know it is not the best :D

Parents Reply Children
No data