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


; ***************************************************************************
; macros

; @param @0 register to use



; ***************************************************************************
; defines



; ***************************************************************************
; data

.dseg



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

.cseg



; ---------------------------------------------------------------------------
; @routine SPISW_Init @global
;

SPISW_Init:
  sec
  ret
; @end



; ---------------------------------------------------------------------------
; @routine SPISW_MasterStart @global
;
; Start SPI software master.
; @clobbers none

SPISW_MasterStart:
  ; setup pins
  sbi SPISW_MOSI_DDR, SPISW_MOSI_PIN  ; MOSI: output
  cbi SPISW_MISO_DDR, SPISW_MISO_PIN  ; MISO: input
  sbi SPISW_SCK_DDR, SPISW_SCK_PIN    ; SCK:  output
  cbi SPISW_SCK_OUTPUT, SPISW_SCK_PIN ; clock low
  ret
; @end



; ---------------------------------------------------------------------------
; @routine SPISW_MasterStop @global
;
; Stop SPI software master. Put all ports to high-Z mode.
; @clobbers none

SPISW_MasterStop:
  ; setup pins
  cbi SPISW_MOSI_DDR, SPISW_MOSI_PIN    ; MOSI: input
  cbi SPISW_MOSI_OUTPUT, SPISW_MOSI_PIN ; disable pullup
  cbi SPISW_MISO_DDR, SPISW_MISO_PIN    ; MISO: input
  cbi SPISW_MISO_OUTPUT, SPISW_MISO_PIN ; disable pullup
  cbi SPISW_SCK_DDR, SPISW_SCK_PIN      ; SCK:  input
  cbi SPISW_SCK_OUTPUT, SPISW_SCK_PIN   ; disable pullup
  ret
; @end



; ---------------------------------------------------------------------------
; @routine SPIHW_MasterExchangeByteMode0 @global
;
; @param r16 byte to send
; @return r16 byte received
; @clobbers r17, r23

SPISW_MasterExchangeByteMode0:
  push r15
    inr r15, SREG
    cli

    ldi r23, 8
SPISW_MasterExchangeByteMode0_loop:
      ; clock low
      cbi SPISW_SCK_OUTPUT, SPISW_SCK_PIN
      nop
  
      ; write MOSI
      sbrs r16, 7
        cbi SPISW_MOSI_OUTPUT, SPISW_MOSI_PIN
      sbrc r16, 7
        sbi SPISW_MOSI_OUTPUT, SPISW_MOSI_PIN
      nop
      lsl r16
  
      ; clock high
      sbi SPISW_SCK_OUTPUT, SPISW_SCK_PIN
      nop
  
      ; read MISO
      lsl r17
      sbic SPISW_MISO_INPUT, SPISW_MISO_PIN
        inc r17
      dec r23
    brne SPISW_MasterExchangeByteMode0_loop
    mov r16, r17

    outr SREG, r15
  pop r15
  ret
; @end






