7

(avery) #1
FORGE

title ‘Hello, world 2’


ld bc, hello
call outstr
ld bc, world
call outstr
halt


hello:
defm ‘Hello, ’
defb 0
world:
defm ‘World!’
defb 13,10,0


outstr:
ld a, (bc)
or 0


ret z
out (1), a
inc bc
jr outstr
Now we can load the address of a string into BC
and call the outstr subroutine. As shown in the code
above, having a subroutine means that we can use it
for different strings without having to repeat the code
each time.
The subroutine is just the code we had before to
output the string. The big difference is that, instead of
jumping past the end of the loop when the zero byte
is found, it returns.

GOING FURTHER
The Z80 has 158 different instructions and ten
addressing modes available; there’s a lot more than
we’ve seen here.
Remember, every CPU has an assembly language,
including the CPU cores in modern MCUs. It’s very
possible to write MCU code in assembly. With
modern C compilers, it’s not necessary to work in
assembly language to get good performance, but it
does give a more detailed understanding of how a
particular MCU or CPU works.
If you want to explore the Z80 and its assembly
language with some real hardware and don’t want to
build your own Z80 computer, you can get RC2014 on
Tindie. The project has a GitHub repo with plenty of
information and tools: github.com/RC2014Z80.
There are a variety of sites dedicated to information
on the Z80 and its usage. The z80pack site has plenty,
and z80.info is a great collection of online material on
the Z80 to boot.

JUMP AROUND


The code uses jp instructions. These jump to a
literal address in memory. There’s another way to
do this: the jr (jump-relative) instructions. jr takes
a relative value, i.e. how far to jump backwards
or forwards. This is done with a single byte, so
it’s limited in how far it can jump to between 126
backward, to 129 forward (relative to the address
of the jr opcode). That’s a small limitation, and
the advantages are that it takes one less byte of
machine code, and it doesn’t use a literal address,
so the code can be loaded into different places in
memory. That can be quite handy at times.

Below
Despite being over 40
years old, Z80 chips
are still made today

The CPU has a
program counter
(PC) register
that contains the
address of the
next instruction to
be executed.

QUICK TIP

Free download pdf