Demo of queue for controller button presses

Discuss technical or other issues relating to programming the Nintendo Entertainment System, Famicom, or compatible systems.

Moderator: Moderators

Post Reply
User avatar
blargg
Posts: 3715
Joined: Mon Sep 27, 2004 8:33 am
Location: Central Texas, USA
Contact:

Demo of queue for controller button presses

Post by blargg » Sun Feb 24, 2008 11:15 pm

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: Select all

; 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

Post Reply