Skip to content

Machine and instruction cycles

The machine cycle is the PIC18 time base. With crystal frequency f_osc:

CM = 4 / f_osc

Why the 4? The crystal sets the clock rate. One pulse lasts 1 / f_osc.

With a 20 MHz crystal (20 million pulses per second), each pulse lasts 0.05 µs — that is, 1 / 20,000,000 s = 0.00000005 s.

The PIC18 does not finish one instruction in a single pulse. Internally it splits the work into 4 clock stages (Q1, Q2, Q3, Q4). One simple instruction needs 4 crystal pulses. So the machine cycle is 4 times longer than one pulse:

CM = 4 × (1 / f_osc) = 4 / f_osc

In short: the crystal tells you how long one pulse is; the 4 tells you how many pulses one instruction uses in the course model.

Crystal (f_osc)1 pulse (1/f_osc)CM = 4 pulses
4 MHz0.25 µs1 µs
20 MHz0.05 µs0.2 µs

For 3 ms @ 20 MHz: target Σ CI = 15,000 (3000 µs / 0.2 µs).

InstructionCycles
MOVLW, MOVWF, NOP1
GOTO, BRA, CALL, RETURN2
DECFSZ1 if no skip; 2 when skipping at zero

Most software delay loops look like this:

BUCLE
DECFSZ CONTADOR,F ; subtract 1 from counter
BRA BUCLE ; loop back if not zero yet

What does DECFSZ do? It subtracts 1 from the counter, then checks the result:

SituationWhat happens nextDECFSZ cycles
Counter not zero yetContinue to the next line (BRA)1 cycle
Counter is zeroSkip the next line (does not run BRA)2 cycles

Key idea: BRA only runs while the counter is still non-zero. On the last pass, DECFSZ skips BRA and the loop ends.

PassValue beforeAfter −1Zero?DECFSZDoes BRA run?
132No1 cycleYes
221No1 cycleYes
310Yes2 cyclesNo (skipped)

Totals for N = 3:

  • DECFSZ: 3 passes → 1 + 1 + 2 = 4 cycles (= N + 1).
  • BRA: 2 passes → 2 × 2 = 4 cycles (= 2 × (N − 1)).

If the counter starts at N and counts down to 0:

DECFSZ → (N − 1) × 1 cycle + 1 × 2 cycles = N + 1 cycles
BRA → (N − 1) × 2 cycles = 2 × (N − 1) cycles

PDF example (N = 200): DECFSZ → 199×1 + 1×2 = 201 cycles. BRA → 199×2 = 398 cycles.

PIC18 pipeline = instruction overlap (exam multiple choice). For delay math, use Table 4.1 as given and sum Σ CI.

Delay = CM × Σ CI
  1. List each instruction and cycles.
  2. Count repetitions.
  3. Sum Σ CI.
  4. Multiply by CM.
  5. Tune with NOP if needed.

Ejercicio · Parcial

Quick check

20 MHz, Σ CI = 605 → delay = 605 × 0.2 µs = 121 µs (PDF example, N=200).

Next: Delay loops.

Interactive exam

Machine and instruction cycles

Based on: Clase Tema 4 y 5.pdf

0 of 0 answered

The machine cycle (CM) formula is...
With a 20 MHz crystal, CM equals...
In Table 4.1, MOVLW and MOVWF use...
DECFSZ uses more cycles when...
Pipeline overlap in the partial exam refers to...
For 3 ms @ 20 MHz you need Σ CI approximately...