; ***************************************************************************
; 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_BYTEREAD_H
#define AVR_MODULES_COM2W2_BYTEREAD_H


.cseg



; ---------------------------------------------------------------------------
; @routine com2w2RecvByteWaitForQuietClk
;
; Wait until the clock line is consistently high for 1ms.
;
; @clobbers r18, r20, r22

com2w2RecvByteWaitForQuietClk:
  ldi r18, 200
com2w2RecvByteWaitForQuietClk_loop:
      ldi r20, 100                                  ; wait up to 1ms for clock high (R20, R22)
      rcall com2w2WaitForClockLowMulti10Us          ; (r20, r22)
      brcs com2w2RecvByteWaitForQuietClk_waitForLow
      dec r18
    brne com2w2RecvByteWaitForQuietClk_loop
    rjmp com2w2RecvByteWaitForQuietClk_ret
com2w2RecvByteWaitForQuietClk_waitForLow:
    ldi r20, 100                                    ; wait up to 1ms for clock low (R20, R22)
    rcall com2w2WaitForClockLowMulti10Us
    brcc com2w2RecvByteWaitForQuietClk_ret          ; not low within 1ms, assume line is quiet
  brne com2w2RecvByteWaitForQuietClk_loop
com2w2RecvByteWaitForQuietClk_ret:
  ret



; ---------------------------------------------------------------------------
; @routine com2w2RecvByte
;
; @return CFLAG set if byte received, cleared on error
; @return r16 byte received
; @clobbers r17, r18, r20, r22

com2w2RecvByte:
  ldi r17, 8
  clr r16
com2w2RecvByte_loop:
    ldi r20, 100                         ; wait up to 1ms for clock low
    rcall com2w2WaitForClockLowMulti10Us  ; (R20, R22)
    brcc com2w2RecvByte_end
    ldi r20, 100                         ; wait up to 1ms for clock high
    rcall com2w2WaitForClockHighMulti10Us ; (R20, R22)
    brcc com2w2RecvByte_end
    ; handle received bit
    inr r18, COM_DATA_INPUT
    andi r18, (1<<COM_DATA_PIN)
    clc
    breq com2w2RecvByte_clockData
    sec
com2w2RecvByte_clockData:
    ror r16
    dec r17
  brne com2w2RecvByte_loop
  sec
com2w2RecvByte_end:
  ret
; @end




#endif


