EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 64
Assembly: Exact Timing Loops
Counting cycles on purpose.
Each instruction takes a known number of clock cycles, so a loop can produce a precise delay. Total time equals cycles divided by the clock frequency.
At 1 MHz one cycle is 1 microsecond. A loop that takes 3 cycles per pass and runs 100 times gives 300 microseconds, plus a few cycles of setup.
Interrupts stretch the delay, so disable them or use a hardware timer when accuracy matters.
EXAMPLE
; generic teaching syntax: assume LOAD=1 cycle, SUB=1, JNZ=2 when taken
LOAD R1, 100 ; 1 cycle
w: SUB R1, 1 ; 1 cycle
JNZ w ; 2 cycles taken (1 on the last pass)
; about 3 x 100 cycles in total