#ifndef F_CPU
	#error "F_CPU must be defined!"
#endif

#if F_CPU < 4000000
	#warning "F_CPU too low, possible wrong delay"
#endif

#define CYCLES_PER_US (F_CPU/1000000)
#define C4PUS (CYCLES_PER_US/4)
#define DVUS(x) (C4PUS*x)

.macro DELAY_uS
	ldi	XH, HIGH(DVUS(@0))
	ldi	XL, LOW(DVUS(@0))
	rcall	Wait4xCycles
.endm


.macro DELAY_mS
	ldi	YL,low(@0)
	ldi	YH,high(@0)
	rcall	WaitMiliseconds
.endm


;------------------------------------------------------------------------------
; Input : XH:XL - number of CPU cycles to wait (divided by four)
;------------------------------------------------------------------------------
Wait4xCycles:
	sbiw   XH:XL, 1
	brne   Wait4xCycles
	ret

;------------------------------------------------------------------------------
; Input : temp - number of miliseconds to wait
;------------------------------------------------------------------------------
;WaitMiliseconds:
;	push temp
;WaitMsLoop:
;	ldi    XH,HIGH(DVUS(500))
;	ldi    XL,LOW(DVUS(500))
;	rcall  Wait4xCycles
;	ldi    XH,HIGH(DVUS(500))
;	ldi    XL,LOW(DVUS(500))
;	rcall  Wait4xCycles
;	dec    temp
;	brne   WaitMsLoop
;	pop    temp
;	ret

;------------------------------------------------------------------------------
; Input : YH:YL - number of miliseconds to wait, использует Temp
; таймер каждую милисекунду отнимает 1 от Y, пока тот не достигнет 0
;------------------------------------------------------------------------------
WaitMiliSeconds:
	ldi	temp,1<<SE
	out	MCUCR,temp	; IDLE SLEEP
WMS_SLL:
	sleep			; спим.
	tst	YL
	brne	WMS_SLL		; спим до сл. прерывания
	tst	YH
	brne	WMS_SLL		; спим до сл. прерывания
	clr	temp
	out	MCUCR,temp	; со сна

	ret
