; Supporting "functions" to wait a specific number of instruction cycles
;
; ### license
;
; These functions are called by the wait_* macros in handy.inc
; SIDE EFFECTS: W and STATUS are unchanged
; 

        list p = 16f688
        include p16f688.inc

wait_functions: code

 global WAIT_10_support
 global WAIT_8_support
 global WAIT_7_support
 global WAIT_6_support
 global WAIT_5_support
 global WAIT_4_support

WAIT_10_support:
        goto    WAIT_8_support  ; 2 for GOTO, +WAIT_8
WAIT_8_support:
        goto    WAIT_6_support  ; 2 for GOTO, +WAIT_6
WAIT_7_support:
        nop
        ; FALLTHRU
WAIT_6_support:
        goto    WAIT_4_support  ; 2 for GOTO, +WAIT_4
WAIT_5_support:
        nop
        ; FALLTHRU
WAIT_4_support:
        return                  ; 2 for the original CALL, 2 for RETURN


; Perform a blocking wait for a period of time. No other operations
; are performed (except interrupts, of course).
;
; Entry:
;   W: 0-255 loops of waiting 32.8ms per loop (when running at 8Mhz)
;
; Exit:
;   W == 0
;   Carry, Zero are SET
;
; ASSUMED: Bank 0. 8Mhz operation.
 global blockwait
blockwait:
        ; Convert loop-count into until-overlow.
        ;   Example: 0 becomes 0xFF, and immediately overflows.
        ;            1 becomes 0xFE, and runs 1 loop until overflow.
        sublw   0xFF

next_wait:
        ; Wait (another) round of 32.8ms delay.
        addlw   1
        skpnc
        return

        ; Reset the timer, then begin waiting for it.
        clrf    TMR0

        ; Note that the Timer0 Interrupt Flag (T0IF) gets set upon
        ; overflow. Interrupts are not enabled, so the flag gets set
        ; and nothing more happens. But we need to clear it, so that
        ; we can look for it getting raised at the next overflow.
        bcf     INTCON, T0IF

        ; Loop until Timer0 overflows.
wait_for_timer:
        btfss   INTCON, T0IF
        goto    wait_for_timer

        ; Timer has overflowed. 32.8ms has passed. Go for another wait.
        goto    next_wait


; stupid assemblers don't realize EOF means *end*
        end
