.module asmFunc
.area HOME
.area CODE
.include "inc/stm8l.s"

; device modes	
.equ WAIT, 0x80 
.equ GETCMD, 0x81
.equ RESETCMD, 0x40
; WRITEBYTE		equ	0x02
; ENUMERATION		equ	0x03
; options bits
.equ NO_TRANSCEIVE_BIT, 7
.equ PRESENCE_BIT, 6

.globl _tim3_capture_handler
_tim3_capture_handler:
	clr	TIM3_SR1
	;//clr	TIM2_SMCR
	btjt	_mode, #NO_TRANSCEIVE_BIT, get_impuls_length	;t1uh_10
	clr	TIM2_SMCR   ;//#######
	srl	_byteToTransceive
	jrnc	test_presence_flag
	mov	TIM2_SMCR, _Tim2Smcr	

test_presence_flag:
	btjf	_mode, #PRESENCE_BIT, get_impuls_length
	;//clr	TIM3_SR1
	mov	_mode, #GETCMD
	iret
get_impuls_length:
	ld	A, TIM3_CCR2H
	ld	XH, A
	ld	A, TIM3_CCR2L
	ld	XL, A


	cpw	X, _min_reset
	jrult	test_get_mode

	cpw	X, _max_reset
	jrult	proc_reset
	mov	_mode, WAIT
	clr	_bOverdrive
	call	_SetSpeedMode
	iret
test_get_mode:
	btjt	_mode, #NO_TRANSCEIVE_BIT, test_received_bit
call_tim3_captured:	
	call	_tim3_captured
	iret
test_received_bit:
	cpw	X, _bit_range
	jrugt	shift_received_bit_mask
	ld	A, _byteReceived
	or	A, _byteReceivedMask
	ld	_byteReceived, A
shift_received_bit_mask:
	sll	_byteReceivedMask
	jrc	call_tim3_captured
	iret

proc_reset:
	mov	TIM2_ARRH, _presence
	mov	TIM2_ARRL, _presence + 1
	bset	TIM2_CR1, #0	;tim2 start
	mov	_mode, #RESETCMD
	
	bset	GPIOC_ODR, #3	;CS_OFF
	clr	_bSelected
	clr	TIM2_SR1
	clr	_bitCounter
	clr	_byteReceived
	clr	_byteToTransceive
	mov	_byteReceivedMask, #1
	iret
;-------------------------------------------------------------------------------
.globl _acc_data_ready_handler
_acc_data_ready_handler:
	call _LIS3DH_DataReady_Handler
	iret
;-------------------------------------------------------------------------------
.globl _tim4_update_handler
_tim4_update_handler:
	call _WatchdogRefresh
	iret
;-------------------------------------------------------------------------------
.equ LAST_SAMPLE, 5
.equ HI_BITS_MASK, 0xF0
.equ LO_BITS_MASK, 0x0F
.globl _ASM_FillFifo
_ASM_FillFifo: ; X - SampleBuffer, Y - FifoBuffer[iFifoWrite]
	push 	A
	pushw	X
	pushw	Y
	
	ld		A, (X)		;OUT_XL = X1 << 4
	and		A, #HI_BITS_MASK
	or		A, #LAST_SAMPLE
	ld		(Y), A	;last mark, X1 -> fifo
	incw	X
	incw	Y
	ld		A, (X)	;OUT_XH = X2 | X3 << 4
	ld		(Y), A	;X2, X3 -> fifo
	incw	X
	incw	Y
	ld		A, (X)	;OUT_YL = Y1 << 4
	swap	A
	and		A, #LO_BITS_MASK
	ld		(Y), A	;Y1
	incw	X
	ld		A, (X)	;OUT_YH
	and		A, #LO_BITS_MASK
	swap	A
	or		A, (Y)	;Y1 | Y2
	ld		(Y), A	;Y1, Y2 -> fifo
	incw	Y
	ld		A, (X)	;OUT_YH
	and		A, #HI_BITS_MASK
	swap	A
	ld		(Y), A	;Y3
	incw	X
	ld		A, (X)	;OUT_ZL << 4
	and		A, #HI_BITS_MASK
	or		A, (Y)	;Y3 | Z1
	ld		(Y), A	;Y3, Z1 -> fifo
	incw	X
	incw	Y
	ld		A, (X)	;Z2, Z3
	ld		(Y), A	;Z2, Z3 -> fifo
	
	popw	Y
	popw	X
	pop 	A
	ret