Skip to main content

7. Delay Implementation Without Library

Delays can be created using nested loops that consume a certain number of clock cycles.

Delay Calculation Concept:

  • ATmega328P on Arduino Uno runs at 16 MHz (16 million clock cycles per second)
  • 1 millisecond = 16,000 clock cycles
  • DEC instruction takes 1 cycle, BRNE takes 2 cycles (if branch taken)

Delay Implementation Examples:

; Delay approximately 1 second (with nested loop)
delay_1s:
    LDI R18, 64          ; Outer counter
outer_loop:
    LDI R24, lo8(62500)  ; Inner counter low byte
    LDI R25, hi8(62500)  ; Inner counter high byte
inner_loop:
    SBIW R24, 1          ; Subtract 16-bit counter (2 cycles)
    BRNE inner_loop      ; Loop if not 0 (2 cycles if taken)
    DEC R18              ; Subtract outer counter
    BRNE outer_loop      ; Loop outer if not 0
    RET

; Simple delay with single loop
delay_simple:
    LDI R16, 255         ; Load counter
delay_loop:
    DEC R16              ; Decrement counter (1 cycle)
    BRNE delay_loop      ; Branch if not zero (2 cycles)
    RET                  ; Return (approximately 765 cycles total)