GameBoy Assembly Language Primer


GameBoy CPU Registers

The GameBoy has instructions & registers similar to the Intel 8080, Intel 8085, & Zilog Z80 microprocessors. It has eight 8-bit registers A,B,C,D,E,F,H,L and two 16-bit registers SP & PC:

15....8 7......0
AF
BC
DE
HL
SP
PC

Some instructions, however, allow you to use the registers A,B,C,D,E,H, & L as 16-bit registers by pairing them up in the following manner: AF,BC,DE, & HL. The F register is indirectly accessible by the programmer and is used to store the results of various math operations.

The PC, or Program Counter, register points to the next instruction to be executed in the GameBoy memory. The SP, or Stack Pointer, register points to the current stack position.


Program Counter

On power up, the GameBoy Program Counter is initialized to $100 (100 hex) and the instruction found at this location in ROM is executed. The Program Counter from this point on is controlled, indirectly, by the program instructions themselves that were generated by the programmer of the ROM cart.

Stack Pointer

A big key to understanding programming in assembly language on the GameBoy is understanding the concept of a stack pointer. A familiarity with assembly language for other processors helps greatly as the concepts are the same.

The GameBoy Stack Pointer is used to keep track of the top of the "stack". The stack is used for saving variables, saving return addresses, passing arguments to subroutines, and various other uses that might be conceived by the individual programmer.

The instructions CALL, PUSH, and RST all put information onto the stack. The instructions POP, RET, and RETI all take information off of the stack. (Interrupts put a return address on the stack and remove it at their completion as well.) As information is put onto the stack, the stack grows downward in RAM memory. As a result, the Stack Pointer should always be initialized at the highest location of RAM space that has been allocated for use by the stack. For instance, if a programmer wishes to locate the Stack Pointer at the top of low RAM space ($C000-$DFFF) he would set the Stack Pointer to $E000 using the command LD SP,$E000. (The Stack Pointer automatically decrements before it puts something onto the stack so it is perfectly acceptable to assign it a value which points to a memory address which is one location past the end of available RAM.)

The GameBoy stack pointer is initialized to $FFFE on power up but a programmer should not rely on this setting and rather should explicitly set its value.

Flag Register

76543210
ZNHC00 00