Writing a while loop in assembly

jnhyf picture jnhyf · May 16, 2011 · Viewed 16.5k times · Source

I'm trying to write a while loop in assembly with a 6502 processor and I cannot figure out how to write the hexadecimal code. I've seen examples written using the shorthand where there is a label for where the loop should begin and end but I do not see anything for the actual hex code.

The two codes I see being useful are:

  1. Comparing a byte in memory to the X reg (shorthand: CPX, hex: EC). This sets the Z flag to zero if equal and
  2. Branch X bytes if Z flag = 0 (shorthand: BNE, hex: D0)

Answer

Pete Wilson picture Pete Wilson · May 16, 2011

Here's a place for you to start. The page features a cross-assembler that you can run on your PC. That could be a good dev platform for you.

Before doing anything, you have to understand the theory of operation of the 6502. Then you have to understand the software-development process that includes:

-- preparing a "source file," so called, of symbolic instructions that you call "shorthand"
-- using an assembler, translating that source file into machine instructions that the 6502 understands
-- loading the translation into the 6502
-- telling the 6502 to execute the translated machine instructions

Your example program tries to copy LEN memory bytes from SRC to DST.

You format it like this:

      LDX #0    ; Start with the first byte 
_LOOP LDA SRC,X ; load a byte from SRC into the A register 
      STA DST,X ; store that byte into DST
      INX       ; bump the index register to point to the next SRC and DST locations 
      CPX #LEN  ; have we moved LEN characters?  
      BNE _LOOP ; if not, go move the next one

After you have added more statement lines (like END, for example); and after you have defined SRC, DST, and LEN, you save the whole thing in a file called, let's say, cploop.txt.

Then you tell the assembler to translate it. The assembler comes out with a file of binary 6502 machine code that cam be represented as the hex bytes you're talking about.

You feed that file of machine code to the simulated 6502. Then you somehow tell the 6502 to execute the operations that the machine code embodies.