Software - Delay routines

In the following routines, branches must not cross page boundaries!

Delay A+constant cycles (subroutine)

For A >= 7, a 7 cycle loop subtracts 7 from the accumulator until it is less than 7. The remaining cases (A = 0 to 6) are documented in the comments.

; 25+A cycles (including JSR), 19 bytes (excluding JSR)
;
; The branches must not cross page boundaries!
;
                  ;       Cycles              Accumulator         Carry flag
                  ; 0  1  2  3  4  5  6          (hex)           0 1 2 3 4 5 6

       JSR DELAYA ; 6  6  6  6  6  6  6   00 01 02 03 04 05 06

DLY0   SBC #7
DELAYA CMP #7     ; 2  2  2  2  2  2  2   00 01 02 03 04 05 06   0 0 0 0 0 0 0
       BCS DLY0   ; 2  2  2  2  2  2  2   00 01 02 03 04 05 06   0 0 0 0 0 0 0
       LSR        ; 2  2  2  2  2  2  2   00 00 01 01 02 02 03   0 1 0 1 0 1 0
       BCS DLY1   ; 2  3  2  3  2  3  2   00 00 01 01 02 02 03   0 1 0 1 0 1 0
DLY1   BEQ DLY2   ; 3  3  2  2  2  2  2   00 00 01 01 02 02 03   0 1 0 1 0 1 0
       LSR        ;       2  2  2  2  2         00 00 01 01 01       1 1 0 0 1
       BEQ DLY3   ;       3  3  2  2  2         00 00 01 01 01       1 1 0 0 1
       BCC DLY3   ;             3  3  2               01 01 01           0 0 1
DLY2   BNE DLY3   ; 2  2              3   00 00             01   0 1         0
DLY3   RTS        ; 6  6  6  6  6  6  6   00 00 00 00 01 01 01   0 1 1 1 0 0 1
;
; Total cycles:    25 26 27 28 29 30 31

Delay A+constant cycles (inline)

A 5 cycle loop subtracts 5 from the accumulator until the carry is clear, leaving A in the range $FB to $FF; these 5 cases are documented in the comments. When inlining this code, make sure the branches do not cross a page boundary.

; 15+A cycles, 16 bytes
;
; The branches must not cross page boundaries!
;
                  ;    Cycles        Accumulator     Carry flag
                  ; 0  1  2  3  4       (hex)        0 1 2 3 4

DELAYA SEC        ; 2  2  2  2  2   00 01 02 03 04   1 1 1 1 1
DLY1   SBC #5     ; 2  2  2  2  2   FB FC FD FE FF   0 0 0 0 0
       BCS DLY1   ; 2  2  2  2  2   FB FC FD FE FF   0 0 0 0 0
       LSR        ; 2  2  2  2  2   7D 7E 7E 7F 7F   1 0 1 0 1
       BCC DLY2   ; 2  3  2  3  2   7D 7E 7E 7F 7F   1 0 1 0 1
DLY2   SBC #$7E   ; 2  2  2  2  2   FF FF 00 00 01   0 0 1 1 1
       BCC DLY3   ; 3  3  2  2  2   FF FF 00 00 01   0 0 1 1 1
       BEQ DLY3   ;       3  3  2         00 00 01       1 1 1
       BNE DLY3   ;             3               01           1
DLY3
;
; Total cycles:    15 16 17 18 19

Delay 18+13(65536Y+256A+X) cycles

This routine uses a 13-cycle loop.

   INY
.1 NOP
   NOP
.2 CPX #1
   DEX
   SBC #0
   BCS .1
   DEY
   BNE .2
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License