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.
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:
; 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.
| Instruction | Operation | Skip when | Cycles (no skip) | Cycles (with skip) |
|---|---|---|---|---|
DECFSZ f, d | f = f − 1 | result = 0 | 1 | 2 |
INCFSZ f, d | f = f + 1 | result = 0 (overflow) | 1 | 2 |
BTFSC f, b | tests bit b of f | bit = 0 | 1 | 2 |
BTFSS f, b | tests bit b of f | bit = 1 | 1 | 2 |
GOTO label | PC ← 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:
; 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
; 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.
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:
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.
; 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:
; 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 ✓
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:
; 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:
; 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:
; 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.
; 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!)
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.
; 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.
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.
; 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
| Technique | Cycles/iteration | Overhead instructions | Memory | Best 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.
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.