Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Arduino Stack Pointer

I have Arduino Mega board with ATmega 2560 chip on it. I've been searching for a few days now and haven't found any clues on how to do this:

I declared a temporary array of bytes as:

volatile byte tempStack[256];

What I then want to do is set the stack pointer to this piece of RAM (if it even is possible?).

Say that I have something already on the stack

tempStack[255] = ...;
tempStack[254] = ...;
tempStack[253] = ...;
tempStack[252] = ...;
tempStack[251] = ...;
tempStack[250] = ...; <--- SP

Now, first ambiguous thing I found out is that some say that the stack pointer points to the first free location right beneath the last used location (in this case tempStack[249]), and the other say that it points to the last used (as marked above). Which one is it? In datasheet it only says that the stack pointer always points to the top of the stack, which of course is obvious, just which byte?

No matter how it is, I still can't seem to set the stack pointer to, say point to tempStack[250]. I tried this:

SP = (word)(&tempstack[250])

This doesn't seem to work, doesn't change the SP at all (as far as I could tell).

Also, I tried:

word addr = (word)(&tempstack[250]);

static volatile byte _spx;

_spx = (byte)(addr >> 0);
__asm__ volatile
(
  "mov r16, %0\n"
  "out 0x3d, r16\n"
  :"=r"(_spx)
);
_spx = (byte)(addr >> 8);
__asm__ volatile
(
  "mov r16, %0\n"
  "out 0x3e, r16\n"
  :"=r"(_spx)
);

This didn't seem to help as well (datasheet says 0x3d is spl, 0x3e is sph).

Another thing that is bugging me is, addresses should be 2 bytes long? Datasheet says that ret and reti instructions pop 3 bytes from the stack (they actually say that the stack pointer is incremented by 3, which should mean what I said). Also I wasn't able to find if the memory is little-endian or big-endian, so, which one is it? In both ways, shouldn't it still be 2 bytes, not 3? What I could have guessed is that the third byte is status register for reti, but it doesn't fit other descriptions.

So, to summarize all questions:

  1. Can you change the stack pointer to point to your custom chunk of RAM?
  2. If yes, how to change the stack pointer?
  3. Does it point to the last used location or first free?
  4. Are the words in memory written in little-endian or big-endian format?
  5. How exactly do ret/reti instructions work (datasheet says 3 bytes get popped, which byte is what)?

Sorry if this is a newbie question, but I just can't seem to crack it.

Comments