Home › Technical Articles › Microcontrollers
Microcontrollers

PIC Assembly: Optimizing loops with Dattalo's techniques

Applying Scott Dattalo's techniques to create efficient loops in PIC Assembly — cycle reduction, precise delays, nested loops, and intelligent use of program memory.

PIC Assembly DECFSZ Loops Optimization Dattalo
SD
This article applies and expands on techniques documented by Scott Dattalo — an electronic engineer and one of the leading references in algorithms for PIC microcontrollers. His original articles are compiled at camposlh.com/dattalo.

Introduction: every cycle counts

Programming in Assembly for PIC microcontrollers is, in essence, an exercise in economy. With a 4 MHz clock and a 1 µs instruction cycle, every wasted instruction has a real and measurable cost. In real-time systems — motor control, signal generation, software serial communication — the difference between a 5-cycle loop and an 8-cycle loop can mean the difference between a system that works and one that fails.

Scott Dattalo, in his technical articles on PIC Assembly, has repeatedly demonstrated that the most efficient way to solve a problem is rarely the most obvious. His techniques for delays, PWM, and signal generation fundamentally depend on well-constructed loops. This article extracts and deepens these patterns, presenting them systematically with practical examples and cycle analysis.

📐
PIC instruction cycle reference (baseline/midrange)
Most PIC instructions execute in 1 instruction cycle = 4 clock cycles. Branch instructions (GOTO, CALL, RETURN) and skip instructions when the skip is taken execute in 2 instruction cycles. When the skip is not taken, it executes in 1 cycle. This is fundamental for calculating precise delays.

1. PIC loop instructions

The midrange PIC (PIC16Fxxx) has no dedicated loop instruction like the 8051's DJNZ. Instead, loops are built from two fundamental instructions that, combined, form the core of almost every loop in PIC Assembly.

DECFSZ — Decrement and Skip if Zero

The DECFSZ f, d instruction decrements register f and skips the next instruction if the result is zero. It is the most important loop instruction on the PIC. Its exact semantics are:

PIC Assembly — DECFSZ 1 cycle (no skip) / 2 cycles (with skip)
; DECFSZ f, d
; d = W (0): result goes to W
; d = F (1): result stays in f (most common)

DECFSZ  COUNT, F       ; COUNT-- ; if COUNT==0, skip next instruction
GOTO    loop_inicio   ; 2 cycles (if not skipped)
; execution continues here when COUNT reaches 0

A critical detail: DECFSZ decrements before testing. This means a register initialized to 0 will run the loop 256 times (0 → 255 → 254 → ... → 1 → 0), not zero times. Initializing it to N runs the loop exactly N times.

INCFSZ — Increment and Skip if Zero

The complementary INCFSZ f, d instruction increments and skips if the result is zero (8-bit overflow). It is less common for simple counting loops, but useful in specific optimization patterns we will see later.

InstructionOperationSkip whenCycles (no skip)Cycles (with skip)
DECFSZ f, df = f − 1result = 012
INCFSZ f, df = f + 1result = 0 (overflow)12
BTFSC f, btests bit b of fbit = 012
BTFSS f, btests bit b of fbit = 112
GOTO labelPC ← label—2—

2. The basic loop and its real cost

The simplest loop in PIC Assembly — counting from N down to 0 — seems trivial, but already reveals the first optimization opportunity. Compare the two versions below:

✗ Naive version — 4 cycles/iteration
; Initialization
    MOVLW  D'10'
    MOVWF  COUNT

loop:
    ; ... work here ...
    DECF   COUNT, F    ; 1 cycle
    BTFSS  STATUS, Z  ; 1 cycle
    GOTO   loop        ; 2 cycles
; Total overhead: 4 cycles/iteration
✓ With DECFSZ — 3 cycles/iteration
; Initialization
    MOVLW  D'10'
    MOVWF  COUNT

loop:
    ; ... work here ...
    DECFSZ COUNT, F    ; 1 cycle (2 on the last one)
    GOTO   loop        ; 2 cycles
; Total overhead: 3 cycles/iteration
; Saving: 25% less overhead

The DECFSZ version removes one instruction per iteration. For a 256-iteration loop, that is 256 cycles saved — at a 4 MHz clock, 256 µs less pure overhead. In the inner loops of critical algorithms, this difference multiplies.

💡
Dattalo's technique: eliminating the GOTO with NOP
In some cases the GOTO can be removed entirely by inverting the loop structure: instead of skipping the GOTO when zero, skip the NOP (or the next useful instruction) when not zero. This works when the loop body fits in a linear block of code. We will see this technique in the delays section.

3. Precise delays: Dattalo's technique

Generating precise delays without using hardware timers is one of the most classic problems in PIC Assembly. The naive approach — a simple decrement loop — works, but wastes cycles and makes exact time calculation difficult. Dattalo documented a family of techniques that allow arbitrarily precise delays with minimal code.

The fundamental delay formula

A delay loop with DECFSZ and GOTO has the following exact cost:

Tdelay = 3 × N − 1 instruction cycles

Where N is the initial counter value (1 to 256). The "−1" comes from the fact that on the last iteration DECFSZ takes 2 cycles (skip taken) but the GOTO is not executed, saving 1 cycle. For N = 0 (256 iterations): T = 3 × 256 − 1 = 767 cycles.

PIC Assembly — Basic calibrated delay 3N − 1 cycles
; Delay of exactly (3*N - 1) instruction cycles
; For N=100: 299 cycles = 299 µs @ 4MHz
; For N=0 (256): 767 cycles = 767 µs @ 4MHz

delay_3N:
    MOVLW  N              ; 1 cycle (outside the loop)
    MOVWF  COUNT          ; 1 cycle (outside the loop)
delay_loop:
    DECFSZ COUNT, F      ; 1 cycle (2 on the last one)
    GOTO   delay_loop    ; 2 cycles
    RETURN               ; 2 cycles (if called via CALL)

Fine-tuning: delays not multiples of 3

The problem with the 3-cycle loop is that it only produces delays that are multiples of 3 (minus 1). For arbitrary delays, Dattalo uses the NOP padding technique before or after the loop:

PIC Assembly — Exactly 100 cycles delay 100 exact cycles
; We want exactly 100 cycles.
; 3*N - 1 = 100  →  N = 33.67 (not an integer!)
; Solution: use N=33 → 98 cycles, + 2 NOPs = 100 cycles
; OR: use N=34 → 101 cycles, but that is 1 too many...
; Better: N=34 → 101 cycles, remove 1 NOP from the overhead

delay_100:
    MOVLW  D'33'          ; 1 cycle
    MOVWF  COUNT          ; 1 cycle
    NOP                  ; 1 cycle  ← fine tuning
    NOP                  ; 1 cycle  ← fine tuning
delay_100_loop:
    DECFSZ COUNT, F      ; 1 cycle (2 on the last one)
    GOTO   delay_100_loop ; 2 cycles
; Total: 2 (setup) + 2 (NOPs) + (3*33 - 1) = 4 + 98 = 102
; Hmm, 2 too many. Adjust: N=33, 1 NOP
; 2 (setup) + 1 (NOP) + (3*33 - 1) = 3 + 98 = 101
; For exactly 100 without setup in the critical path:

delay_100_v2:
    MOVLW  D'32'          ; 1 cycle
    MOVWF  COUNT          ; 1 cycle
    GOTO   $+1            ; 2 cycles (2-cycle NOP)
delay_100_v2_loop:
    DECFSZ COUNT, F      ; 1 cycle (2 on the last one)
    GOTO   delay_100_v2_loop ; 2 cycles
; Total: 1+1+2 + (3*32 - 1) = 4 + 95 = 99 cycles
; + 1 NOP = exactly 100 cycles ✓
💬
Dattalo's insight: GOTO $+1 as a 2-cycle NOP
The GOTO $+1 trick (a jump to the next address) is a 2-cycle NOP — useful when you need to add exactly 2 cycles of adjustment without using two separate NOPs. Dattalo uses this pattern extensively in his PWM and delay articles to align timing without wasting program memory.

4. Nested loops: multiplying the reach

A single 8-bit loop generates at most 767 delay cycles (N=256). For longer delays — milliseconds or seconds — nested loops are necessary. Dattalo's technique for nested loops is elegant: each outer level multiplies the reach of the inner loop.

Millisecond delay

With a 4 MHz clock (1 instruction cycle = 1 µs), a 1 ms delay requires 1000 cycles. A simple 8-bit loop reaches at most 767 cycles, so we need two levels:

PIC Assembly — 1 ms delay @ 4 MHz ≈ 1000 cycles
; Delay of approximately 1 ms with a 4 MHz clock
; Strategy: outer loop (N2) × inner loop (N1)
; Cost per outer iteration: 3*N1 - 1 + 3 cycles (outer overhead)
; Total ≈ (3*N1 + 2) * N2
;
; For 1000 cycles: N1=100, N2=3 → (3*100+2)*3 = 916 (too short)
; N1=110, N2=3 → (332)*3 = 996 ≈ 1000 ✓

delay_1ms:
    MOVLW  D'3'
    MOVWF  OUTER          ; outer loop: 3 iterations
outer_loop:
    MOVLW  D'110'
    MOVWF  INNER          ; inner loop: 110 iterations
inner_loop:
    DECFSZ INNER, F      ; 1 cycle (2 on the last one)
    GOTO   inner_loop    ; 2 cycles → 3 cycles/inner iteration
    DECFSZ OUTER, F      ; 1 cycle (2 on the last one)
    GOTO   outer_loop    ; 2 cycles → 3 cycles/outer iteration
    RETURN               ; 2 cycles

; Exact calculation:
; Setup: 2 cycles (outer MOVLW + MOVWF)
; Per outer iteration:
; - 2 cycles (inner MOVLW + MOVWF)
; - (3*110 - 1) = 329 cycles (inner loop)
; - 3 cycles (outer DECFSZ + GOTO, except the last)
; Total per outer iteration: 334 cycles
; 3 outer iterations: 3 * 334 - 1 = 1001 cycles ≈ 1 ms ✓

Parametric delay: passing N via W

A very useful variation documented by Dattalo is the parametric delay — where the number of milliseconds is passed in the W register before the call. This allows a single reusable delay sub-routine:

PIC Assembly — Parametric delay (N × 1ms)
; Call with: MOVLW N ; CALL delay_Nms
; Runs a delay of N milliseconds (N = 1..255)

delay_Nms:
    MOVWF  MS_COUNT       ; save N
ms_outer:
    MOVLW  D'110'
    MOVWF  INNER
ms_inner:
    DECFSZ INNER, F
    GOTO   ms_inner      ; ~1 ms loop
    DECFSZ MS_COUNT, F   ; decrement ms counter
    GOTO   ms_outer
    RETURN

; Usage:
    MOVLW  D'250'         ; 250 ms
    CALL   delay_Nms

    MOVLW  D'1'           ; 1 ms
    CALL   delay_Nms

5. The loop without GOTO: Dattalo's technique for ultra-efficient loops

Dattalo's most elegant loop technique is removing the GOTO altogether. Instead of using DECFSZ + GOTO (3 cycles/iteration), he uses an inverted skip structure to build a loop of just 2 cycles per iteration — a 33% reduction.

The idea is: instead of skipping the GOTO when the counter reaches zero, skip the DECFSZ (or equivalent) while the counter has not yet reached zero. This is possible when the loop body has exactly 1 instruction:

PIC Assembly — 2-cycle loop (without GOTO) 2N cycles
; Technique: INCFSZ with the counter initialized to (256 - N)
; The loop runs N times in exactly 2N cycles
; (vs 3N-1 cycles with DECFSZ+GOTO)

; For N=100 iterations: initialize with 256-100 = 156
    MOVLW  256 - 100      ; = 156 = 0x9C
    MOVWF  COUNT

loop_2cycles:
    INCFSZ COUNT, F      ; 1 cycle (2 on the last one: overflow to 0)
    GOTO   loop_2cycles  ; 2 cycles... wait, it is still 3!

; The truly 2-cycle version uses RETLW (for tables):
; Or uses Dattalo's "unrolled loop" pattern:

; DATTALO PATTERN: 2-cycle loop with DECFSZ + NOP
; Works when the loop "work" is exactly 1 instruction

loop_dattalo_2:
    NOP                  ; 1 cycle ← loop work
    DECFSZ COUNT, F      ; 1 cycle (2 on the last one)
    GOTO   loop_dattalo_2 ; 2 cycles
; Still 3 cycles... The real saving comes from the unrolled loop

Unrolled loop (loop unrolling)

Dattalo's most powerful technique for high-performance loops is loop unrolling: instead of running N iterations of a loop, duplicate the loop body N times in the code. This removes the control overhead completely (DECFSZ + GOTO = 3 cycles) at the cost of more program memory.

PIC Assembly — Comparison: loop vs. unrolled
; Task: execute "BSF PORTB, 0" 4 times

; LOOP VERSION: 4 * 3 - 1 = 11 cycles + 3 setup = 14 cycles
; Memory: 4 instructions
    MOVLW  D'4'
    MOVWF  COUNT
loop_v:
    BSF    PORTB, 0
    DECFSZ COUNT, F
    GOTO   loop_v

; UNROLLED VERSION: 4 cycles, no overhead
; Memory: 4 instructions (same cost!)
    BSF    PORTB, 0      ; 1 cycle
    BSF    PORTB, 0      ; 1 cycle
    BSF    PORTB, 0      ; 1 cycle
    BSF    PORTB, 0      ; 1 cycle
; Saving: 10 cycles (71% faster!)
⚠️
Loop unrolling: when is it worth it?
Loop unrolling is advantageous when N is small (≤ 8) and the loop body is simple. For large N, the program memory cost outweighs the speed gain. The PIC16F has 2K or 8K program words — use loop unrolling judiciously in time-critical sections, not as a general rule.

6. RETLW tables: the loop that doesn't look like a loop

One of the most elegant techniques in PIC Assembly, widely used by Dattalo in his signal-generation articles, is the lookup table implemented with RETLW. In essence it is an indexed-access "loop" over program memory — but with no control overhead at all.

PIC Assembly — RETLW table (Dattalo's technique) 3 cycles per access (CALL + RETLW)
; Sine table with 16 samples (0 to 90 degrees)
; Values in Q0.8 fixed point (0 to 255 = 0.0 to 1.0)

; Access: W = index (0..15), CALL sine_table → W = value
sine_table:
    ADDWF  PCL, F         ; PC = PC + W (jump to entry)
    RETLW  0x00           ; sin(0°)   = 0
    RETLW  0x1B           ; sin(6°)   ≈ 0.105
    RETLW  0x36           ; sin(12°)  ≈ 0.208
    RETLW  0x50           ; sin(18°)  ≈ 0.309
    RETLW  0x67           ; sin(24°)  ≈ 0.407
    RETLW  0x7B           ; sin(30°)  = 0.500
    RETLW  0x8D           ; sin(36°)  ≈ 0.588
    RETLW  0x9B           ; sin(42°)  ≈ 0.669
    RETLW  0xA7           ; sin(48°)  ≈ 0.743
    RETLW  0xB0           ; sin(54°)  ≈ 0.809
    RETLW  0xB8           ; sin(60°)  ≈ 0.866
    RETLW  0xBD           ; sin(66°)  ≈ 0.914
    RETLW  0xC0           ; sin(72°)  ≈ 0.951
    RETLW  0xC1           ; sin(78°)  ≈ 0.978
    RETLW  0xC2           ; sin(84°)  ≈ 0.995
    RETLW  0xC3           ; sin(90°)  = 1.000

; Usage: W = index → CALL sine_table → W = value
    MOVLW  D'7'           ; index 7 = sin(42°)
    CALL   sine_table     ; W = 0x9B ≈ 0.669

The ADDWF PCL, F trick adds the index to the program counter, jumping straight to the right table entry. Each RETLW loads the value into W and returns in 2 cycles. The total cost is 3 cycles per access (1 for ADDWF + 2 for RETLW) — regardless of the table size.

⚠️
Watch out for the page boundary
The ADDWF PCL, F instruction only changes the low 8 bits of the PC. If the table crosses a 256-word boundary (a 256-address page), the access will be wrong. Dattalo recommends always aligning tables to the start of a page with the ORG directive, or making sure the whole table fits within 256 addresses.

7. Loops in PWM generation: applying Dattalo

Dattalo's PWM article (available at camposlh.com/dattalo/pwm.html) shows how well-built loops are the foundation of software PWM generation. The phase-shifted counters technique uses two counters that increment in the same loop, with the output controlled by their overflows.

PIC Assembly — Software PWM (Dattalo's technique) 8-cycle loop per iteration
; Software PWM with phase-shifted counters
; Resolution: 8 bits (256 duty-cycle levels)
; PWM frequency = Fclk / (4 * 256 * loop_cycles)

; Registers:
; RISING  - rising-edge counter
; FALLING - falling-edge counter = 256 - duty_cycle
; PORTB,0 - PWM output

pwm_init:
    CLRF   RISING         ; rising edge counter = 0
    MOVLW  256 - 64       ; duty cycle = 64/256 = 25%
    MOVWF  FALLING

pwm_loop:
    INCFSZ RISING, F      ; 1 cycle (2 on overflow)
    GOTO   $+2            ; 2 cycles (skips BSF)
    BSF    PORTB, 0      ; set output on the rising edge

    INCFSZ FALLING, F     ; 1 cycle (2 on overflow)
    GOTO   $+2            ; 2 cycles (skips BCF)
    BCF    PORTB, 0      ; clear output on the falling edge

    GOTO   pwm_loop       ; 2 cycles

; Cost per normal iteration: 1+2+1+2+2 = 8 cycles
; Cost on the overflow iteration: 2+1+2+1+2 = 8 cycles (symmetric!)
; PWM frequency @ 4MHz: 4MHz / (4 * 8 * 256) ≈ 488 Hz

8. Technique comparison: cycles and memory

TechniqueCycles/iterationOverhead instructionsMemoryBest use
DECF + BTFSS + GOTO 4 3 Low Legacy code, compatibility
DECFSZ + GOTO 3 2 Low General loop, most common pattern
INCFSZ + GOTO $+2 3–4 2–3 Low PWM, overflow counters
Unrolled loop 0 0 High (N × body) Small N, critical timing
RETLW table 3 (access) 1 (ADDWF PCL) N + 1 words Value lookup, signal generation
2-level nested loop ~3 (inner) 4 (2 per level) Low Long delays, N > 256

Conclusion

Dattalo's loop techniques in PIC Assembly are not just optimization tricks — they express a deep understanding of the PIC's Harvard architecture and the real cost of every instruction. The underlying philosophy is always the same: understand what the hardware does at the cycle level and exploit it to the full.

The patterns presented here — DECFSZ + GOTO as the base structure, fine tuning with NOPs and GOTO $+1, nested loops for long delays, loop unrolling for critical sections and RETLW tables for lookup — form a complete vocabulary for writing efficient PIC Assembly. Combined with the PWM and signal-generation techniques documented by Dattalo, they make it possible to implement sophisticated algorithms on microcontrollers with only 2K words of program memory and 68 bytes of RAM.

📚
Related Dattalo articles on the site
PWM Techniques — Software PWM generation techniques using phase-shifted counters and phase accumulators.
Generating Sine Waves in Software — 10 methods for sine wave generation, including RETLW tables and the Goertzel algorithm.
Square Root Theory and Algorithms — Square root algorithms for 8-bit microcontrollers.
LH
Luis H. Campos
Electrical Engineer · camposlh.com
Electrical Engineer with over 10 years of experience in electronic projects, PCB design, and embedded systems. Specialized in PIC, ESP32, and STM32 microcontrollers, firmware and hardware development for industrial and IoT applications.