This page is a mirror of Tepples' nesdev forum mirror (URL TBD).
Last updated on Oct-18-2019 Download

Demo of queue for controller button presses

Demo of queue for controller button presses
by on (#31189)
I wrote a clean example of how to queue controller button/D-pad presses inside an NMI, then read them from the main program outside the NMI. This allows the user to input lots of presses without the game losing any. The size of the queue can be adjusted to up to 128 presses, plenty for most programs. The example prints button presses, then waits half a second before checking the queue again, allowing you to easily queue up a bunch of presses, then watch them properly print out in sequence. Code assembles with ca65.

controller_queue.zip

These are the core routines that implement the queue:
Code:
; Adds byte A to queue
queue_press:
    ldx write_pos
    sta queue,x
    dex
    bpl :+
    ldx #queue_size
:   stx write_pos

    cpx read_pos
    beq queue_overflowed
   
    rts

; Removes byte from queue into A, or 0 if queue is empty
read_queue:
    lda #0
    ldx read_pos
    cpx write_pos
    beq @empty
   
    lda queue,x
    dex
    bpl :+
    ldx #queue_size
:   stx read_pos

@empty:
    cmp #0
    rts