I am having problems using ADC and SBC. These instructions are not adding and/or subracting data properly for me. I am using a "CLC" before every ADC or SBC. But still I am getting unxpected results ( error is +/- 1).
I am pasting my code below:
...
...
STA tileIndexBelow
CLC
SBC #$0F
STA tileIndexRight
CLC
SBC #$02
STA tileIndexLeft
CLC
SBC #$0F
STA tileIndexAbove
CLC
Am I doing anything wrong?
You use SEC before SBCs, not CLC. CLC only comes before ADCs.
CLC
ADC
SEC
SBC
Edit: More detail, clarity
ADC adds the value you give it + the value of the carry bit (Carry = 0, then ADC #$00 adds #$00, Carry Flag is 1, then ADC #$00 adds #$01)
SBC subtracts the value you give it - the opposite of the carry bit. (Carry = 1, then SBC #$00 subtracts #$00. Carry Flag is 0, then SBC #$00 subtracts #$01)
All 6502 family and ARM CPUs use "active low" logic for the borrow in subtraction. Carry=1 means don't borrow; carry=0 means borrow. So most of the time, you'll do SEC before you SBC.
If you want to know why 6502 works this way, I can explain that too.
Think of the carry bit as a 9th bit to the 8 bit operation. Before adding we clear the carry, and if the result overflows, the carry receives this overflow. Before subtracting, we set the carry like if we were preparing a bit to be borrowed in case the operation needs it. If after the operation the carry is still set, the carry didn't need to be borrowed, but if it's clear it was borrowed.