DECFSZ Arithmetic
Decrement a register and skip the next instruction when it reaches 0.
| Syntax | DECFSZ f, d |
|---|---|
| Operands | f: register address 0-127 (bank bits come from STATUS); d: 0 or w puts the result in W, 1 or f puts it back in f |
| Operation | (f) - 1 → destination; skip if the result is 0 |
| Status bits | None |
| Words / cycles | 1 word, 1 (2 if it skips) cycles |
| Encoding | 00 1011 dfff ffff |
How it works
DECFSZ subtracts 1 from register f and skips the next instruction if the result is 0. Followed by GOTO, it is the standard PIC counting loop and the building block of software delays.
Each pass of a DECFSZ/GOTO loop takes 3 instruction cycles (1 + 2), and the final pass, which skips, takes 2. At 4 MHz an instruction cycle is 1 µs.
Example
; DECFSZ example from picsimulator.com/instructions/decfsz.html
list p=16f84a
include <p16f84a.inc>
org 0
movlw 3
movwf 0x20 ; loop counter
clrf 0x21
loop:
incf 0x21, f ; count the passes
decfsz 0x20, f ; 3 -> 2 -> 1 -> 0, skip on 0
goto loop
nop ; 0x21 = 3
The body runs three times. Starting the counter at 0 would run it 256 times, because 0 - 1 wraps to 0xFF.
Open this example in the simulator
Watch out for
- Nested delay loops must reload the inner counter on every outer pass, or every pass after the first runs 256 times.