User:JanSuchy/Sandbox

From Wikipedia, the free encyclopedia

Programming in 6502 machine code on Apple 1

When you turn on Apple 1, a program known as Wozmon allows you to display content of specified addresses on the screen, write to specified addresses and jump to specified address.

Let's write machine code that prints uppercase W on the screen. Wozmon includes a subroutine located at address FFEF that outputs ASCII character stored in the accumulator on the screen. Accumulator is one of the six registers on 6502 CPU.

We will start our program at address 0302. We will use instruction A9 "load immediate value into accumulator", hexadecimal code of uppercase W in ASCII is 57. To call a subroutine (instruction 20) at address FFEF, we have to enter in memory hexadecimal numbers 20 EF FF. 6502 uses little endian format, the low byte EF goes before the high byte FF. The last instruction in our program will be a jump back to Wozmon. Wozmon entry point is at address FF1F. We will type 4C 1F FF.
302: A9 57 20 EF FF 4C 1F FF

To verify the program was entered correctly, we can type
302.309

To run the program, we type
302 R

What if we want to print W ten times? We could write 20 EF FF ten times but let's use a loop instead. At the beginning of the program, we will set index register X to A.
300: A2 A

When the program returns from subroutine at FFEF, we will use instruction CA to decrement register X by 1. Apart from changing value in register X, the instruction also updates register F. In case register X contains zeros, zero flag will be set (Fz=1), otherwise Fz will be equal to zero. As long as Fz=0, we will be jumping 6 bytes back to address 0304 using instruction D0. Minus 6 in decimal equals to FA in hexadecimal.
307: CA D0 FA 4C 1F FF

Let's verify the entire program
300.30C

and run it
300 R