Skip to content

Instantly share code, notes, and snippets.

@ISSOtm
Created March 26, 2019 00:05
Show Gist options
  • Save ISSOtm/9fa9484c73fc304e062f1bfb8ab1ed41 to your computer and use it in GitHub Desktop.
Save ISSOtm/9fa9484c73fc304e062f1bfb8ab1ed41 to your computer and use it in GitHub Desktop.
Game Boy joypad-polling routine, featuring tried-and-tested timings (somehow) as well as Up+Down / Left+Right automatic cancelling
ld c, LOW(rP1)
ld a, $20 ; Select D-pad
ld [$ff00+c], a
REPT 6
ld a, [$ff00+c]
ENDR
or $F0 ; Set 4 upper bits (give them consistency)
ld b, a
; Filter impossible D-pad combinations
and $0C ; Filter only Down and Up
ld a, b
jr nz, .notUpAndDown
or $0C ; If both are pressed, "unpress" them
ld b, a
.notUpAndDown
and $03 ; Filter only Left and Right
jr nz, .notLeftAndRight
ld a, b
or $03 ; If both are pressed, "unpress" them
ld b, a
.notLeftAndRight
swap b ; Put D-pad buttons in upper nibble
ld a, $10 ; Select buttons
ld [$ff00+c], a
REPT 6
ld a, [$ff00+c]
ENDR
; You can `and $0F` here and `jr z, .reset` to perform a soft-reset
or $F0 ; Set 4 upper bits
xor b ; Mix with D-pad bits, and invert all bits (such that pressed=1) thanks to "or $F0"
ld b, a
; Release joypad
ld a, $30
ld [$ff00+c], a
ldh a, [hHeldButtons]
cpl
and b
ldh [hPressedButtons], a
ld a, b
ldh [hHeldButtons], a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment