Advanced z80 programming techniques
Hooks
Interrupts
What are interrupts?
Types of interrupts
Type 0
Type 1
Type 2
How to code them
How to install them
Principles
The jump table
Direct LCD Interaction
Principles
Port $10
Writing
Reading
Port $11
Writing
Reading
Optimizations
xor a
A common shortcut to set the accumulator (A) to zero is by xor'ing it against itself:
; instead of doing this
ld a,0
; you can do this
xor a
This is incredibly widespread and won't affect the readability of your code. In fact, it is so common that it might even be more readable than using "ld a,0". But be warned that "xor a" modifies the flags (it sets the z flag and resets the carry, for example) whereas "ld a,0" doesn't modify any flags.
ld (addr),reg16
When writing to two consecutive bytes in memory, it can often be faster and smaller to use a 16-bit register rather than two loads with a.
; rather than
ld a,$10
ld (penCol),a
ld a,$20
ld (penCol),a
; you can do
ld de,$2010
ld (penCol),de
This loads e into (penCol), and d into (penCol+1). penCol+1 is penRow. Keep in mind, however, that using hl to read/write from addresses in memory is (4 t-states) faster and one byte smaller than using de/bc.
X <= A <= Y
If you want to know if the value of the accumulator is between two other values, eg. 10 and 25, you might be tempted to do something like this:
cp 10 ; check if a >= 10
jr c,wrongValue
cp 26 ; check if a <= 25
jr nc,wrongValue
; do whatever you wanted to do
wrongValue:
; ...
However, rather than doing two comparisons and jumps, you can change the first cp into a subtraction. This turns any number less than 10 into a negative number. For example:
sub 10 ; a value of 10 now equals 0
cp 26-10 ; because of the sub 10, we now need to check if a is between 0 and 16, not 10 and 26
jr nc,wrongValue
; do whatever you wanted to do
wrongValue:
; ...
This method lets you avoid the first jr.