Manipulating Stack Memory in PIC18 Microcontroller?

POP Operation on Stack

Stack Memory

The stack memory is a general read/write (RAM) that is used to store the critical information temporarily in a PIC microcontroller. This critical information can be an adress or some data.  Since the CU has a limited number of registers, sometimes the values are stored in the stack memory to ensure that important data is not lost during processing and can be retrieved when needed.

The stack memory can store 21 bits of data because the program counter (PC) is of 21 bits. This means that it is used for storing the address of the next instruction to be executed whenever a call is made in a program. This ensures the PIC where to come back once the call routine is finished using the RETURN keyword.

A 21-bit stack can take values from 000000H (for minimum, set all bits to 0s) to 1FFFFFH (for maximum, set all bits equal to 1).

What is the Stack Pointer?

Since a stack is RAM, there is an internal register called the Stack Pointer (SP) that is used to access the values stored in the stack. So, you can say that the stack pointer is used to point the values stored in it. In PIC microcontroller, the stack pointer is of 5 bits which can take values from 00H to 1Fh. The total number of slots available are equal to 2^5=32.

When PIC is powered up, the stack pointer register has the value of 00H which means the first slot is not available for storing the values in stack.

Stack Memory and Stack Pointer
Stack Memory and Stack Pointer

PUSH and POP Operation Example

Consider the following code example, where I will show how the PUSH and POP operations are performed in stack. After the first call, PC points to the address 000008H. This address is PUSHED into stack.

PUSH Operation in Stack

The PUSH operation is used for storing values at the Top of Stack (TOS) the stack. When the PUSH operation is performed, first the SP is incremented and then the value is stored in it.

PUSH Operation on Stack

POP Operation in Stack

The POP operation is used for removing values from the Top of Stack (TOS). When the POP operation is performed, first the data is removed and then the SP decrements.

POP Operation on Stack
POP Operation on Stack

Leave a Reply

Your email address will not be published. Required fields are marked *