Button combo issues

This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade.
View original topic
Button combo issues
by on (#108311)
I'm having some issues with my controller code.

Up, down, left and right all work as they should. Any combination of three buttons or more works as expected (opposite directions cancel each other out, up+down+left+right results in no movement). Down+left and down+right also work as expected.

Up+left, however, results in movement up, no left, and up+right results in movement up and double movement right.

Any ideas?

Code:
readctrl:
   lda #$01
    sta $4016
    lda #$00
    sta $4016
       
    ; Read all 8 buttons
    ldx #$08
loop:
    pha
   
    ; Read next button state and mask off low 2 bits.
    ; Compare with $01, which will set carry flag if
    ; either or both bits are set.
    lda $4016
    and #$03
    cmp #$01
   
    ; Now, rotate the carry flag into the top of A,
    ; land shift all the other buttons to the right
    pla
    ror a
   
    dex
    bne loop
   
   tax
   
   txa
   and #$10 ; up
   beq :+
   lda #$ff
   adc $0204
   sta $0204
   
   : txa
   and #$20 ; down
   beq :+
   lda #$01
   adc $0204
   sta $0204
   
   : txa
   and #$40 ; left
   beq :+
   lda #$ff
   adc $0207
   sta $0207
   
   : txa
   and #$80 ; right
   beq :+
   lda #$01
   adc $0207
   sta $0207

   lda #$02
   sta $4014 ; OAM DMA from RAM page 2


The exact same behavior is observed both in emu and on real hardware.
Re: Button combo issues
by on (#108314)
One thing that's clear is that you're not clearing the carry before the additions. This could explain the kind of behavior you're getting.
Re: Button combo issues
by on (#108315)
Yep, that was the issue. Hadn't thought of that. Thanks!

Now I have a game that says hello world and that has an LSD trip colored box sprite that can be moved around the screen. 3 days ago I was struggling to even compile the init code. This was a glorious weekend :D