; ***************************************************************************
; copyright   : (C) 2026 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.   *
; ***************************************************************************

#ifndef AVR_MODULES_COM2W2_BYTEWRITE_H
#define AVR_MODULES_COM2W2_BYTEWRITE_H


.cseg



; ---------------------------------------------------------------------------
; @routine com2w2SendBytes
;
; @param  R18 number of bytes to send
; @param X pointer to bytes to send
; @param Y pointer to interface data in SRAM
; @clobbers: r16, r18, X (r17, r22)

com2w2SendBytes:
com2w2SendBytes_loop:
    rcall com2w2ClkSetLow                     ; (none)
    rcall com2w2WaitTime1                      ; longer wait period (R22)
    ld r16, X+
    rcall com2w2SendByte                      ; (R16, R17, R22)
    dec r18
  brne com2w2SendBytes_loop
  ret
; @end



; ---------------------------------------------------------------------------
; @routine com2w2SendByte
;
; @param  R16 byte to send
; @clobbers: r16, r17 (r22)

com2w2SendByte:
  push r15
    in r15, SREG
    ldi r17, 8
com2w2SendByte_loop:
      M_COM2WCLKSETLOW
      out SREG, r15                          ; probably enable irqs
      rcall com2w2WaitTime1                  ; wait for longer time (R22)
      lsr r16
      brcs com2w2SendByte_send1
      M_COM2WDATASETLOW
      rjmp com2w2SendByte_sent
com2w2SendByte_send1:
      M_COM2WDATASETHIGH
com2w2SendByte_sent:
      Utils_WaitNanoSecs 5000, 0, r22        ; wait for very short time to ensure data is stable when clock rises
      cli                                    ; ensure time period by disabling irqs
      M_COM2WCLKSETHIGH
      rcall com2w2WaitTime2                  ; wait for shorter time (R22)
      dec r17
    brne com2w2SendByte_loop
    out SREG, r15
  pop r15
  rcall com2w2WaitTime2                      ; wait for shorter time (R22)
  M_COM2WDATASETHIGH                         ; ensure data line is high
  ret
; @end



#endif

