; ***************************************************************************
; copyright   : (C) 2023 by Martin Preuss
; email       : martin@libchipcard.de
;
; ***************************************************************************
; * This file is part of the project "AqHome".                              *
; * Please see toplevel file COPYING of that project for license details.   *
; ***************************************************************************



; ***************************************************************************
; code


.cseg


; ---------------------------------------------------------------------------
; wait depending on lowest byte of uid.
;
; Wait interval is between 100ms and 25s (i.e. 255*100ms). This is used to avoid
; all nodes on the network trying to send messages at the exact same time (e.g. after
; power outage which would affect all nodes at the same time).
;
; IN:
; - nothing
; OUT:
; - nothing
; REGS: R16 (R22, R24)

flashWaitDependingOnUid:
  lds r16, flashUid
  tst r16
  brne flashWaitDependingOnUid_l1
  ldi r16, 17
flashWaitDependingOnUid_l1:
  rjmp flashWaitForMulti100ms



; ---------------------------------------------------------------------------
; wait for multiples of 100ms.
;
; IN:
; - R16: number of 100ms loops
; OUT:
; - nothing
; REGS: R16 (R22, R24)

flashWaitForMulti100ms:
flashWaitForMulti100ms_loop:
    rcall flashWaitFor100ms      ; (R22, R24)
    dec r16
  brne flashWaitForMulti100ms_loop
  ret



; ---------------------------------------------------------------------------
; wait for 100 milliseconds.
;
; IN:
; - nothing
; OUT:
; - nothing
; REGS: R24 (R22)

flashWaitFor100ms:
  ldi r24, 100
  rjmp flashWaitForMillisecs



; ---------------------------------------------------------------------------
; @routine flashWaitForMillisecs
; wait for multiples of 100 milliseconds.
;
; @param R24  time to wait in milliseconds
; @clobbers R24 (R22)

flashWaitForMillisecs:
    push r24
      rcall flashWaitFor1ms      ; (R22, R24)
    pop r24
    dec r24
  brne flashWaitForMillisecs
  ret
; @end



; ---------------------------------------------------------------------------
; wait for 1 millisecond.
;
; IN:
; - nothing
; OUT:
; - nothing
; REGS: R24 (R22)

flashWaitFor1ms:
  ldi r24, 100
flashWaitFor1ms_loop:
    rcall Utils_WaitFor10MicroSecs                ; wait for 10us (R22)
    dec r24
  brne flashWaitFor1ms_loop
  ret



