The Stack Overflow/Underflow Reset is available on newer 12F/16F devices and the more advanced 18F devices. A Hardware Stack is equipped on PIC® MCU devices to store the return address when interrupt or call type instructions are implemented and need to store a return address. That return address is stored on the hardware stack. Programs can have multiple layers of redirection, thus the hardware stack has multiple layers of storage. As a redirection occurs the return addresses are stacked on top of each other in sequential order. This is where the name stack comes from.
There may be times when the software gets lost or enters an area that creates a redirection beyond the stack limit or encounters a return from redirection request when there wasn't a return address on the stack. In either case, the stack will overflow or underflow the stack list and return a value that will be meaningless to the program and will most likely cause further issues in the applications operation. Providing a way to reset the code when this unintended overflow or underflow occurs is the function of the Stack Overflow/Underflow Reset.
In the event of of an overflow or underflow, the reset places the Program Counter back to the beginning of program memory (org 0) and the Stack Pointer (STKPTR) is reset back to the first location of the hardware stack.
The depth of the hardware stack is dependent on the device being used. The data sheet for the device will describe the stack limits. The illustration shown below is an example of a stack filled 6 levels deep of a 16 level stack. Any branches beyond 10 more levels or returns from branch beyond six levels will cause a stack overflow or stack underflow reset if enabled.
Enable/Disable Stack Overflow Reset
The STVREN bit is in a Configuration Register and enables or disables the overflow/underflow reset option. This is done at program time and cannot be changed via software. Setting the bit to a one enables the reset.
Stack Overflow/Underflow Indicator
When a Stack Overflow/Underflow reset occurs, the status bits in the PCON register indicate if an overflow or underflow caused the reset to occur. A one setting indicates the cause of the reset. At the top of the main code loop, these bits can be monitored to determine if anything needs to run based on a stack overflow or stack underflow reset.