why do we need to initialize stack pointer in the begnning of the program of AVR assembly programming
-
1I'm confused, what link ? – Mathieu VIALES Oct 26 '17 at 08:32
3 Answers
Your assembly program is calling a subroutine. When you do that, the return address is stored on the stack using the stack pointer, so it's important to initialize it to point to an appropriate place in RAM. The ATmega328P datasheet says:
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture.

- 84,103
- 24
- 152
- 189
Very simple, the answer comes straight frm the datasheet - look for Stack Pointer. Stack pointer initial value is 0x0000, meaning it would point to register R0 (which adress is 0x0000) if not initialized. You would not want that, as you use R0 and other register to perform operations. That is why you want to set the stack to some other memory area, specifically to the Internal SRAM (a general purpose RAM area).

- 50
- 5
It depends on the microcontroller you are using. Older AVRs had the stack pointer initialized by hardware to 0x0000. You had to change that to something sensible (most often RAMEND
) before using subroutines or interrupts. Newer AVRs have the stack pointer initialized by hardware to RAMEND
, so you do not need software initialization.
You will have to check the datasheet to see whether your particular MCU needs that software initialization or not. Where in doubt, do it anyway: it doesn't hurt (it takes only 4 CPU cycles) and it can make your code more portable. Also, a bootloader may have altered the stack pointer.

- 3,416
- 15
- 18