How can i change the stack size on Arduino?

Hi everyone :slight_smile:

I am working on an arduino project using an Arduino Mega board and i came across a bug.

There is a non blocking function in my code and when i try to light a led after this function it’s not working,
the led still remains off.

There is a hudge probability that the problem is related to the stack size.

My question is the following, how can i change the stack size ?

PS : I tried in vain to find a ldscript folder.

I don’t know, isn’t stack related to SRAM?
How about posting your code here?

Yes the stack is related to SRAM and i would like to know how can i change the stack size in the SRAM.

When you compile a C++ program for the Arduino (or Mega) then the stack pointer register SP, whihc is made up of two 8 bit registers SPH and SPL, are initialised with a value which corresponds to the top of available RAM. Here’s the startup code for an Arduino UNO, which has 2048 bytes of SRAM:

000000b8 <__ctors_end>:
  b8:	11 24       	eor	r1, r1
  ba:	1f be       	out	0x3f, r1	; 63
  bc:	cf ef       	ldi	r28, 0xFF	; 255
  be:	d8 e0       	ldi	r29, 0x08	; 8
  c0:	de bf       	out	0x3e, r29	; 62
  c2:	cd bf       	out	0x3d, r28	; 61

Registers r28 and r29 are loaded with 255 + (8 * 256), which is the initial stack pointer address. That works out at address 2303 decimal. Registers 0x3e and 0x3d are SPH and SPL respectively, so the stack is initially loaded with the address of the top of RAM. The memeory map for an ATmega328P is:
ATmega328P_stack

You can see that where the device has 2048 bytes of SRAM, the stack address is initialised to the top of that area, at address 0x08FF - which is what we see in the code above.

The stack grows downwards as it is used and may, if you have a recursive loop that never terminates, for example, start overwriting data in the lower end of SRAM.

TL;DR: There is no stack size! The stack size is all of available SRAM.

I suspect there’s a bug in the code you are running. Are you able to post it here?

Cheers,
Norm.

3 Likes

Hi, sorry for the delay in my response

You were right, there was a bug in my code, but thank you very much for all your explanation on the stack on Arduino
it will be very useful for me.

again thank you for your help :slight_smile:

1 Like