;___________________IR_Variabeln___________________________________
.dseg
TCNT0_H:	.byte 1
TCNT0_old:	.byte 1
TCNT0_H_old:	.byte 1
IR_High:	.byte 1
IR_Low:	.byte 1
IR_Timeout:	.byte 1 
IR_Status:	.byte 1 
.cseg
;__________________________________________________________________
.equ	T0_Timeout = 19

IR_init:	ldi r16,0
	sts TCNT0_H,r16
	sts TCNT0_old,r16
	sts TCNT0_H_old,r16
	ldi r16,32 
	sts IR_Status,r16
	sts IR_Timeout,r16


	in r16,TCCR0
	andi r16,255-(1<<CS02|1<<CS01|1<<CS00)
;	ori r16,(0<<CS02|0<<CS01|0<<CS00) ;stop
;	ori r16,(0<<CS02|0<<CS01|1<<CS00) ;/1
;	ori r16,(0<<CS02|1<<CS01|0<<CS00) ;/8
;	ori r16,(0<<CS02|1<<CS01|1<<CS00) ;/64
	ori r16,(1<<CS02|0<<CS01|0<<CS00) ;/256
;	ori r16,(1<<CS02|0<<CS01|1<<CS00) ;/1024
;	ori r16,(1<<CS02|1<<CS01|0<<CS00) ;Ext von Pin T0 falling Edge
;	ori r16,(1<<CS02|1<<CS01|1<<CS00) ;Ext von Pin T0 rising  Edge
	out TCCR0,r16

	in r16,TIMSK
	ori r16,(1<<TOIE0)
	out TIMSK,r16 ;Timer 0 overflow

	in r16,mcucr
	andi r16,255-(1<<ISC00|1<<ISC01)
	ori  r16,(1<<ISC00)
	out MCUCR,r16
	in r16,GIMSK
	andi r16,255-(1<<INT0)
	ori r16,(1<<INT0)
	out GIMSK,r16
	ret

OVF0_:	push r0
	in   r0, SREG
	push r0
	push r16

	lds r16,IR_Timeout
	mov r0,r16
	lds r16,TCNT0_H
	cp r0,r16
	brne PC+6

	lds r16,IR_Status
	ori r16,32
	sts IR_Status,r16

	lds r16,TCNT0_H

	inc r16
	sts TCNT0_H,r16

	pop r16
	pop r0
	out SREG, r0
	pop r0
	reti


INT0_:	push r0
	in   r0, SREG
	push r0
	push r16
	push r17
	push r18
	push r19
	push zl
	push zh

	lds r16,IR_Status
	mov r0,r16         ;Status in R0
	sbis PinD,2
	rjmp Int0_low
 		; Int 0 High
	andi r16,255-32  ;Timeout Flag löschen
	sts IR_Status,r16
	lds r16,TCNT0_H
	subi r16,256-T0_Timeout;Timeout neu setzen
	sts IR_Timeout,r16
	rjmp kein_IR_Timeout

Int0_low:	sbrs r0,5	 ;Timeout gesetzt ?
	rjmp kein_IR_Timeout ;nein

	ldi r17,255          ;ja
	lds r16,TCNT0_H
	sts TCNT0_H_old,r16
	in r16,TCNT0 
	sts TCNT0_old,r16
	rjmp IR_bewerten

kein_IR_Timeout:	lds r17,TCNT0_H  ;Timer nach R17:r16
	in r16,TCNT0 


	lds r18,TCNT0_old
	lds r19,TCNT0_H_old
	sts TCNT0_old,r16
	sts TCNT0_H_old,r17
	sub r16,r18
	sbc r17,r19     ;Pulsdauer berechnen

	
IR_bewerten:	push r16
	mov r16,r17
	rcall TX_out
	pop r16
	rcall TX_out


	pop zh
	pop zl
	pop r19
	pop r18
	pop r17
	pop r16
	pop r0
	out SREG, r0
	pop r0
	reti
		



