PC and SP

z80 » Intermediate

Program Counter

The z80 needs to keep track of where it's executing code. It stores that address in the 16 bit register pc. You can't directly modify this register with regular instructions.

The only way to modify pc is to push a new value onto the Stack and use a ret. The ret will use the last value on the stack as the new Program Counter. It'll jump to that address and start executing code again.

Stack Pointer

When you push and pop stuff on and off the Stack, the Stack Pointer (sp) is updated either with the addition of two bytes by a pop or the subtraction by a push. Remember that the Stack rises in memory as more is pushed onto it.

You can modify sp through a few instructions.

	adc hl,sp
	add hl,sp
	add ix,sp
	add iy,sp
	dec sp
	inc sp
	ex (sp),hl
	ex (sp),ix
	ex (sp),iy
	ld ($c000),sp
	ld sp,($c000)
	ld sp,hl
	ld sp,ix
	ld sp,iy
	ld sp,$2303
	sbc hl,sp

Sometimes, you may run into a problem with exiting your program and not having time to pop everything you pushed on the Stack. Here's a simple routine to call before you start executing stuff in your program. It saves the sp. To exit the program, jump to this routine; it will restore the sp and exit safely. Call SaveSP at the start of the program and use jp SafeExit to exit.

SafeExit:
	ld sp,(SavedSP)		;get back saved sp
	ret			;exit
SaveSP:
	ld (SavedSP),sp		;save sp
	ret			;go back
SavedSP:	.dw 0		;memory to save sp


More from z80 » Intermediate
All the Flags // Debugging // Down-Left Bug // _GetKey Codes // Logical Operators // Memory, ROM, RAM, and Safe Areas // Miscellaneous Instructions // PC and SP // Random Numbers // TI's ROM Calls // Restart Commands // Simulated 16-bit Addition // The Stack // Tables and Arrays // Text Display // Variables