2
votes

i'm having some trouble with the following code for a 6502 machine:

C000 LDA #$00
C002 STA $FE
C004 LDA #$20
C006 STA $FF
C008 LDY #$08
C00A LDX #$00
C00C DEY
C00D CPY #$FF
C00F BEQ $C01B
C011 LDA ($FE),Y
C013 CMP #$2F
C015 BPL $C00C
C017 INX
C018 JMP $C00C
C01B BRK

The exercise is to store the numbers 2, 1 and 4 starting from the address 2000 and say what are the values of A, X and Y.

I'm "running" my code with pen and paper but I got stuck at C011 for the following reason:
LDA ($FE),Y
It loads in A the value stored at the memory address calculated this way:

  1. pick $FE value (that at first is 00)
  2. Add the value of Y (that at first iteration is 7)
  3. I now have 07
  4. Load A with the value stored at 07

Is this correct? Am I missing something? If I'm not, where do I use the values stored in 2000 2001 and 2002 ?

Thanks in advance..

3

3 Answers

4
votes

pick $FE value (that at first is 00)

Actually, it loads a 16-bit value from $FE, and then adds Y to that value to get the effective address.

You've stored $00 at $FE and $20 at $FF, so the 16-bit value loaded from $FE will be $2000

where do I use the values stored in 2000 2001 and 2002

When Y has the value 0, 1, and 2. The loop will continue until Y wraps around from 0 to $FF.


See "10) Post-indexed indirect" in 6502.txt.

2
votes

This addressing mode is called post-indexed indirect and is used only with the Y register. The effective address is formed from the (little-endian) contents of address $00FE and $00FF and Y is added to that address.

You stored $2000 in those two page zero locations, and Y holds 7 so the effective address is $2007, beyond the three bytes of data you wish to access.

Note that could have accessed the array directly as

LDA $2000,Y

but the advantage of the indirect method is that you don't need to know the address in advance, for example you could select one of several tables to be indexed depending on run-time conditions.

2
votes

No, you're not correct. You're missing the meaning of LDA ($FE),Y which uses the indirect indexed (as opposed to indexed indirect) addressing mode. Indirect means the value inside the parentheses is the address of a 16-bit pointer, low byte first. That's the $00 and $20 you set up earlier, so $2000.

The indexing is done with Y, and your loop exit condition is based on Y, so you have that. The value of A is the last value read, so you have that too.

But your comment & question on Weather Vane's answer is very relevant. The values in the other memory locations matter because of the CMP #$2F and subsequent BPL and INX. CMP acts like a subtract, and the N flag is set if the compared register < compared memory; see here.

So the value of X depends on those other memory values.