;***********************************************************************
;* f osc = 8 MHz internal RC
;* mega8A
;* 
;* добавлено автоопределение DS1307 / PCF8563
;* исправлено промаргивание температуры при одном датчике
;* исправлено отставание смены температуры от переключения светодиодов дом\улица
;* непроверено
;***********************************************************************

.include	"m8def.inc"
.nolist				
.equ		PeriodTermo = 4	;seconds to change Temperature




.def		timecnt  = R7	;счетчик прерываний
.def		celscnt  = R8	;счетчик прерываний
.def		btnumber = R9	;для DS18B20
.def		iodata   = R10	;для DS18B20
.def		iodataL  = R11	;для DS18B20
.def		resmode	 = R12
;.def				 = R13
.def		keycnt	 = R14
.def		delaycnt = R15	;счетчик для задержки
.def		temp     = R16
.def		buferL   = R17
.def		buferH   = R18
.def		flags    = R19
.equ		f_TERMO  = 0
.equ		f_minus  = 1
.equ		f_TIME	 = 2
.equ		f_I2CErr = 3
.equ		f_Tout	 = 4
.equ		f_less10 = 5
.equ		f_VL	 = 6
.equ		f_Terr	 = 7
.def		flags2	 = R20
.equ		f_correct= 0
.equ		f_PCF	 = 1
.equ		f_ToIND	 = 2
.def		razryad  = R21
.def		setupcnt = R22
.def		seconds	 = R23
.def		minutes	 = R24
;.def			 = R25


;			XL		 = R26
;			XH		 = R27
;			YL		 = R28
;			YH		 = R29
;			ZL		 = R30
;			ZH		 = R31
.equ	S_Port	= PORTD			; сегменты
;					76543210
.equ	S_a		= 0b00000100
.equ	S_b		= 0b00000010
.equ	S_c		= 0b10000000
.equ	S_d		= 0b01000000
.equ	S_e		= 0b00100000
.equ	S_f		= 0b00001000
.equ	S_g		= 0b00010000
.equ	S_h		= 0b00000001
.equ	Off		= 0b00000000
.equ	R_Port	= PORTB			; разряды
.equ	K_Port	= PORTB			; кнопки
.equ	KeyPin	= 0

.equ	PortS	= PORTC			; датчики
.equ	DatPin	= 0
.equ	CLKPin	= 1
.equ	ToutPin	= 2
.equ	TinPin	= 3
;.equ	SDA		= 4
;.equ	SCL		= 5

.equ	modebutt= 1	;PB
.equ	downbutt= 2	;PB
.equ	upbutt  = 3	;PB
.equ	notbutt	= 4	;PB
.equ	bspeed=28

.equ	PCF_ADR			= 0xA3	;for WR A2
.equ	DS_ADR			= 0xD1	;for WR D0
.equ	CONVERTT    	= 0x44
.equ	READSCRATCHPAD	= 0xBE
.equ	SKIPROM			= 0xCC

;for pcf
;0x100	CONTROL_STATUS_1
;0x101	CONTROL_STATUS_2
;0x102	VL_SECONDS
;0x103	MINUTES
;0x104	HOURS
;0x105	DAYS
;0x106	WEEKDAYS
;0x107	CENTURY_MONTHS
;0x108	YEARS
;0x109	MINUTE_ALARM
;0x10A	HOUR_ALARM
;0x10B	DAY_ALARM
;0x10C	WEEKDAY_ALARM
;0x10D	CLKOUT_CONTROL
;0x10E	TIMER_CONTROL
;0x10F	TIMER

;for ds
; 0x00 CH=0  3x 10sec     4x 1sec
; 0x01  0    3x 10min     4x 1min
; 0x02  0 PMAM=0 2x 10H   4x 1H
; 0x03  0    0   0  0     0  3x day of week
; 0x04  0    0   2x 10D   4x 1D
; 0x05  0    0   0 10M    4x 1M
; 0x06  4x 10Year         4x 1Year
; 0x07 OUT=0 0   0 SQWE=0 0  0 RS1=0 RS0=0
;ch - clock halt
;OUT - level when SQWE=0
;SQWE - Square-Wave Enable
;RS - rate select


;* $060-0FF empty
;* $100-10F PCF data
;* $110-114 Data to display
;* $118-11E Segment data
;* $120-124 Result of hex2dec
;* $127 oldsec
;* $130 correct sec per week
;* $13E,$13F result, pos of filter
;* $140-15F filter data
.equ	RAM_PCF			=0x00

.MACRO macroWaitLdStatus
		out		TWCR, temp
		clr		buferL
wait_twint:
		inc		buferL
		breq	PC+5		;--\
		in		temp, TWCR	;	|
		sbrs	temp, TWINT	;   |
		rjmp	wait_twint	;   |
		in		temp, TWSR	;<--/
		andi 	temp,0xF8
.ENDM
;--------Начало главного програмного кода-----------

.cseg						;выбор сегмента програмного кода
.org 0						;установка текущего адреса на 0

;********************************************************************
;*               Векторы прерываний 								*        
;********************************************************************
		rjmp	RESET	;0x000 Pin, Power-on, Brown-out, Watchdog Reset
		reti			;0x001 INT0 External Interrupt Request 0
		reti			;0x002 INT1 External Interrupt Request 1
		reti			;0x003 TIMER2_COMP Timer/Counter2 Compare Match
		reti			;0x004 TIMER2_OVF Timer/Counter2 Overflow
		reti			;0x005 TIMER1_CAPT Timer/Counter1 Capture Event
		rjmp	COMPA	;0x006 TIMER1_COMPA Timer/Counter1 Compare Match A
		rjmp	COMPB	;0x007 TIMER1_COMPB Timer/Counter1 Compare Match B
		reti			;0x008 TIMER1_OVF Timer/Counter1 Overflow
		reti			;0x009 TIMER0_OVF Timer/Counter0 Overflow
		reti			;0x00A SPI_STC Serial Transfer Complete
		reti			;0x00B USART_RXC USART, Rx Complete
		reti			;0x00C USART_UDRE USART Data Register Empty
		reti			;0x00D USART_TXC USART, Tx Complete
		rjmp	ADCCC	;0x00E ADC ADC Conversion Complete
		reti			;0x00F EE_RDY EEPROM Ready
		reti			;0x010 ANA_COMP Analog Comparator
		reti			;0x011 TWI Two-wire Serial Interface
		reti			;0x012 SPM_RDY Store Program Memory Ready

SIMV:
;they will be ON (255-... inverse)
;   -a-
;  f   b
;  |-g-|  
;  e   c
;   -d-
	.db	255-(S_a|S_b|S_c|S_d|S_e|S_f)		,255-(S_b|S_c)				  ;0,1
	.db	255-(S_a|S_b|S_d|S_e|S_g)			,255-(S_a|S_b|S_c|S_d|S_g)	  ;2,3
	.db	255-(S_b|S_c|S_f|S_g)				,255-(S_a|S_c|S_d|S_f|S_g)	  ;4,5
	.db	255-(S_a|S_c|S_d|S_e|S_f|S_g)		,255-(S_a|S_b|S_c)			  ;6,7
	.db	255-(S_a|S_b|S_c|S_d|S_e|S_f|S_g)	,255-(S_a|S_b|S_c|S_d|S_f|S_g);8,9
	.db	255-(S_a|S_d|S_e|S_f|S_g)			,255-(S_e|S_g)				  ;E,r
	.db	255-(S_g)							,255-(S_a|S_f|S_e|S_d)		  ;-,C
	.db	255-(S_d)							,255-Off					  ;_,space
;--------------------------------------------------------
; 10,11 12,13  14
; часы  -  минуты 
; 4  3  2  1   0  bit of PORTB
;--------------------------------------------------------
conversion:		;$110..116->temp->$118..11E
		ldi		ZH,$01
		ldi		ZL,$10
CONV_LOOP:
		ld		temp,Z+
		push	ZH
		push	ZL
		ldi		ZH,High(2*SIMV)
		ldi		ZL,Low (2*SIMV)
		cbr		temp,$F0		; ограничить символы 0-F
		add		ZL,temp
		lpm		temp,Z
		pop		ZL
		pop		ZH

		sbrc	flags2,f_ToIND
		rjmp	next1
		cpi		ZL,0x15				;in
		brne	next2
		cbr		temp,S_h
next1:
		cpi		ZL,0x17				;out
		brne	next2
		cbr		temp,S_h
next2:
		cpi		ZL,0x16				;point
		brne	next3
		sbrs	flags,f_less10
		cbr		temp,S_h
next3:
		cpi		ZL,0x13				;dpoint
		brne	next4
		cpi		setupcnt,3
		breq	next4
		sbrc	celscnt,0
		rjmp	next4
		cbr		temp,S_h
next4:

		std		Z+7,temp		; сохранить в новой области памяти
		cpi		ZL,$17
		brne	CONV_LOOP
		ret
;----------------------------------------------

hex2dec:		;in buferH,buferL out $120-124 (used temp) 
		ldi		ZH,$01
		ldi		ZL,$20
		clr		temp
five:
		subi	buferL,LOW(10000)	
		sbci	buferH,HIGH(10000)
		inc		temp
		brcc	five
		subi	temp,(-$2F)
		st		Z+,temp
		subi	buferL,LOW(-10000)	
		sbci	buferH,HIGH(-10000)
		clr		temp
four:
		subi	buferL,LOW(1000)	
		sbci	buferH,HIGH(1000)
		inc		temp
		brcc	four
		subi	temp,(-$2F)
		st		Z+,temp
		subi	buferL,LOW(-1000)	
		sbci	buferH,HIGH(-1000)
		clr		temp
tres:
		subi	buferL,LOW(100)	
		sbci	buferH,HIGH(100)
		inc		temp
		brcc	tres
		subi	temp,(-$2F)
		st		Z+,temp
		subi	buferL,LOW(-100)	
		clr		temp
dous:
		subi	buferL,10
		inc		temp
		brcc	dous
		subi	temp,(-$2F)
		st		Z+,temp
		subi	buferL,-$3A
		st		Z+,buferL
		ret

I2C_SETADRES:
		cbr		flags,(1<<f_I2CERR)
;send start 
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTA)
		macroWaitLdStatus
		cpi 	temp,0x08
		brne	SETADRESERROR
;start transmission of address
		ldi		temp, PCF_ADR			;const PCF adres
		sbrs	flags2,f_PCF
		ldi		temp, DS_ADR			;DS adres to read
		cbr		temp,(1<<0)				;to write
		out		TWDR, temp
		ldi		temp,(1<<TWINT)|(1<<TWEN)
		macroWaitLdStatus
		cpi 	temp,0x18
		brne	SETADRESERROR
;set $00 addres
		ldi		temp, $00
		out		TWDR, temp
		ldi		temp,(1<<TWINT)|(1<<TWEN)
		macroWaitLdStatus
		cpi 	temp,0x28
		brne	SETADRESERROR
		ret							;Adres has been writen
SETADRESERROR:
;		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTO)
;		out		TWCR, temp
		sbr		flags,(1<<f_I2CERR)
		ret							;Adres error

I2C_READ:
		sbrc	flags,f_I2CERR
		rjmp	I2C_ERROR
;Send ReStart
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTA)
		macroWaitLdStatus
		cpi 	temp,0x10
		breq	PC+2
		rjmp	I2C_ERROR
;Send Slave Adres
		ldi		temp, PCF_ADR			;PCF adres to read
		sbrs	flags2,f_PCF
		ldi		temp, DS_ADR			;DS adres to read
		out		TWDR, temp
		ldi		temp,(1<<TWINT)|(1<<TWEN)
		macroWaitLdStatus
		cpi 	temp,0x40
		brne	I2C_ERROR
;ReadDATA to Y=0x100 for time
		ldi		YH,0x01
		ldi		YL,RAM_PCF
READ_LOOP:
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWEA)
		macroWaitLdStatus
		cpi 	temp,0x50
		brne	I2C_ERROR
		in		temp,TWDR
		st		Y+,temp
		cpi		YL,RAM_PCF+0x0F
		sbrs	flags2,f_PCF
		cpi		YL,RAM_PCF+0x07
		brcs	READ_LOOP
;last byte noACK
		ldi		temp,(1<<TWINT)|(1<<TWEN)
		macroWaitLdStatus
		in		temp,TWDR
		st		Y+,temp
;Send STOP
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTO)
		out		TWCR, temp
		ret
I2C_ERROR:
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTO)
		out		TWCR, temp
		sbr		flags,(1<<f_I2CERR)
		ret

I2C_WRITE:
		ldi		YH,1
		ldi		YL,RAM_PCF
WRITE_LOOP:
		ld		temp,Y+
		out		TWDR,temp
		ldi		temp,(1<<TWINT)|(1<<TWEN)
		out		TWCR, temp			;start transmission of address
		clr		buferL				;anticrash counter
waitackN:
		inc		buferL
		breq	PC+5				;escape from loop
		in		temp,TWCR
		sbrs	temp,TWINT			;ACK has been received
		rjmp	waitackN
		in		temp,TWSR
		andi	temp,0xF8
		cpi		temp,0x28			;Data Transmitted, ACK has been received
		brne	I2C_ERROR
		cpi		YL,RAM_PCF+16
		brne	WRITE_LOOP
		ldi		temp,(1<<TWINT)|(1<<TWEN)|(1<<TWSTO)
		out		TWCR, temp
		ret


;******************************************************************
;*		            DS18B20 TERMOMETR	@8MHz				  	  *
;******************************************************************
;------------------------------------------------------------------
IN_BYTE:
		cbi		PORTS,TinPin		;0 на DataPin
		cbi		PORTS,ToutPin		;0 на DataPin
		ldi		temp, 8
		mov		btnumber, temp
IN_BIT:
		cli							;Global Interrupt Disable
;---- Momentary low for 2,5us ----
		sbrc	flags,f_Tout
		sbi		PORTS-1,ToutPin
		sbrs	flags,f_Tout
		sbi		PORTS-1,TinPin		;настраиваем DataPin на вывод
		nop							;	\
		nop							;	 nop
		nop							;	/
		ldi		temp,1
		rcall	delay
		sbrc	flags,f_Tout
		cbi		PORTS-1,ToutPin
		sbrs	flags,f_Tout
		cbi		PORTS-1,TinPin		;настраиваем DataPin на ввод
;-------------------------------
		ldi		temp,9				;10 MCS delay
		rcall	delay

		in		temp,PORTS-2
		sbrc	flags,f_Tout
		bst		temp,ToutPin
		sbrs	flags,f_Tout
		bst		temp,TinPin			;Tflag stored

		sec 						;Set Carry
		brts	PC+2				;skip if T Set 
		clc 						;Clear Carry
		ror		iodata
		ldi		temp,53				;54 MCS delay
		rcall	delay
		sei							;Global Interrupt Enable
		dec		btnumber	
		brne	IN_BIT
		ret
;
;------------------------------------------------------------------
OUT_BYTE:   						;outs byte from iodata
		cbi		PORTS,TinPin		;0 на DataPin
		ldi		temp,8
		mov		btnumber,temp
OUT_BIT:
		cli							;Global Interrupt Disable
		ror		iodata
		brcc	OUT_0
;out1
		sbrc	flags,f_Tout		;\
		sbi		PORTS-1,ToutPin		; \
		sbrs	flags,f_Tout		;  \
		sbi		PORTS-1,TinPin		;   настраиваем DataPin на вывод
		nop							;\
		nop							; nop
		nop							;/
		ldi		temp,1
		rcall	delay

		sbrc	flags,f_Tout		;\
		cbi		PORTS-1,ToutPin		; \
		sbrs	flags,f_Tout		;  \
		cbi		PORTS-1,TinPin		;   настраиваем DataPin на ввод

		ldi		temp, 79			;80 MCS delay
		rcall	delay
		rjmp	OUT_0_END		
OUT_0:
		sbrc	flags,f_Tout		;\
		sbi		PORTS-1,ToutPin		; \
		sbrs	flags,f_Tout		;  \
		sbi		PORTS-1,TinPin		;   настраиваем DataPin на вывод

		ldi		temp, 79			;80 MCS delay
		rcall	delay

		sbrc	flags,f_Tout		;\
		cbi		PORTS-1,ToutPin		; \
		sbrs	flags,f_Tout		;  \
		cbi		PORTS-1,TinPin		;   настраиваем DataPin на ввод

		nop							;\
		nop							; nop
		nop							;/
		ldi		temp,1
		rcall	delay
OUT_0_END:
		sei							;Global Interrupt Enable
		dec		btnumber
		brne	OUT_BIT
		ret


INITIALIZING:
		sbr		flags,(1<<f_I2CERR)	; error by default
;настраиваем DataPin на вывод
		sbrc	flags,f_Tout
		sbi		PORTS-1,ToutPin
		sbrs	flags,f_Tout
		sbi		PORTS-1,TinPin
;500 MCS delay
		ldi		temp,249
		rcall	delay
		ldi		temp,249
		rcall	delay
;Global Interrupt Disable
		cli
;настраиваем DataPin на ввод
		sbrc	flags,f_Tout
		cbi		PORTS-1,ToutPin
		sbrs	flags,f_Tout
		cbi		PORTS-1,TinPin		
;52 MCS delay
		ldi		temp, 51			
		rcall	delay
;Global Interrupt Enable
		sei
;Test LowLevel
		in		temp,PORTS-2
		sbrc	flags,f_Tout
		bst		temp,ToutPin
		sbrs	flags,f_Tout
		bst		temp,TinPin			;Tflag stored
		brtc	PC+2				;skip if T Clr 
		ret
;500 MCS delay
		ldi		temp,249
		rcall	delay
		ldi		temp,249
		rcall	delay
;Test HighLevel
		in		temp,PORTS-2
		sbrc	flags,f_Tout
		bst		temp,ToutPin
		sbrs	flags,f_Tout
		bst		temp,TinPin			;Tflag stored
		brts	PC+2				;skip if T Set 
		ret
		cbr		flags,(1<<f_I2CERR)	;noError
		ret
REFRESH:
		ldi		temp,SKIPROM
		mov		iodata,temp
		rcall	OUT_BYTE
		ldi		temp,CONVERTT
		mov		iodata,temp
		rcall	OUT_BYTE
		ret
READDATA:
		ldi		temp,SKIPROM
		mov		iodata,temp
		rcall	OUT_BYTE
		ldi		temp,READSCRATCHPAD
		mov		iodata,temp
		rcall	OUT_BYTE
		rcall	IN_BYTE
		mov		iodataL,iodata				
		rcall	IN_BYTE				;iodata:iodataL xxxSTTTT TTTTDDDD
TEMP2DEC:
		cbr		flags,(1<<f_minus)
		bst		iodata,4			;4bit = minus (Store Bit to T Flag)
;------- преобразование ----------
		brtc	noninverting
		sbrc	flags,f_Tout
		sbr		flags,(1<<f_minus)	;Tin не имеет минуса
		com		iodata
		com		iodataL
		ldi		temp,1
		add		iodataL,temp
		ldi		temp,0			;ldi not change SREG
		adc		iodata,temp
noninverting:
		ldi		temp,160
		mul		temp,iodataL
		mov		iodataL,R1
		mul		temp,iodata
		clr		temp
		add		R0,iodataL
		adc		R1,temp
;for hex2dec
		mov		buferL,R0
		mov		buferH,R1
		rcall	hex2dec
		ret
;-------------------------------------------------------------------

;----------------- delay temp+1 uS ------------
;		ldi		temp,1				;1
delay:						;rcall 	 3
		push	temp				;2
		pop		temp				;2
		nop							;1
		dec		temp				;1
		brne	delay				;2
		ret							;4
;----------------------------------------------

;-------------------------------------------------------------------
;**********************************************************************
;*       НАЧАЛО ПРОГРАММЫ											  *
;**********************************************************************
RESET:
		cli							;запретить все прерывания
		clr		temp
		out		EECR, temp			;обнулить EEPROM Control Register
		out		GICR, temp			;interrupt vectors at start of FlashMEM
		out		MCUCR,temp			;Sleep Disable ;Sleep Mode = Idle
									;Interrupt Sense Control = Low level of INT1(0)
;		out		WDTCR, R30			;Watchdog Disable
		ldi		temp,0x18
		out		WDTCR,temp
		ldi		temp,0x0E			;Watchdog Enable 1sec
		out		WDTCR,temp
;--------Очистка SRAM-------------------------------
		ldi		YL, LOW(RAMEND-0x60)
		ldi		YH, HIGH(RAMEND-0x60)
		ldi		XL, 0x60			;X=0x0060
CLEAR_SRAM:
		st		X+, R30				;R30=0 adress 060..45F
		sbiw	YL, 1				;3FF..0
		brne	CLEAR_SRAM			;branch if not zero

;--------Инициализация стека------------------------
		ldi		temp, LOW(RAMEND)	;выбор адреса вершины стека
		out		SPL, temp			;запись его в регистр стека
		ldi		temp, HIGH(RAMEND)	;выбор адреса вершины стека
		out		SPH, temp			;запись его в регистр стека

;--------Инициализация портов-----------------------
		ldi		temp, 0b11111111	
		out		S_Port-1,temp		;DDR 1=out сегменты
		out		R_Port-1,temp		;DDR 1=out разряды
		ldi		temp, 0b00000000	
		out		PortS-1, temp		;DDR 0=in датчики

		ldi		temp, 0b11111111	
		out		R_Port,temp			;Razryad off
		out		S_Port,temp			;Segment off
		ldi		temp, 0b00000000	
		out		PortS,temp			;PORT 0=no pull-up

		cbi		K_Port-1,KeyPin		;buttons in
		cbi		K_Port,KeyPin		;buttons no pullup
		cbi		PortS-1,TinPin		;термометр
		sbi		PortS-1,DatPin		;registers
		sbi		PortS-1,ClkPin		;registers
;-------- Инициализация таймера TMR1 -----------------
		ldi		temp,0b00000000
		out		TCCR1A,temp
		ldi		temp,0b00001001		;WGM=CTC CLKio/1
		out		TCCR1B,temp

		ldi		temp,high(11428)	;16000=1428,6us/0,125us
		out		OCR1AH,temp
		ldi		temp,low(11428)		;1428,6us*7 = 10ms=100Hz
		out		OCR1AL,temp

		ldi		temp,high(16000)	;>A
		out		OCR1BH,temp
		ldi		temp,low(16000)
		out		OCR1BL,temp

		in		temp,TIMSK
		ori		temp,(1<<OCIE1A)|(1<<OCIE1B)
		out		TIMSK,temp			;compa,b
;-------- Инициализация АЦП --------------------------
		ldi		temp,0b10001110 	;ADC=On Prescaler=64 (125kHz @ 8MHz)
		out		ADCSRA,temp			;	Int Enable
		ldi		temp,0b00000110		;Multiplexer to ADC6 right adjusted
		out		ADMUX,temp
;-------- Инициализация TWI --------------------------
;SCL freq = Clk/(16+2*TWBR*Prescaller)
		ldi		temp, 32			;8000k/(16+2*32)=100k
		out		TWBR, temp			;bitrate	
		ldi		temp, (1<<TWEN)
		out		TWCR, temp			;Enable TWI
		ldi		temp, (1<<TWEN)
		out		TWSR, temp			;status
;-------- Read EEPROM mega8 ------------------------------
		ldi		YH,1
		ldi		YL,0x30
		ldi		temp,0				;EEPROM adress
		out		eearh,temp			
		out		eearl,temp			
		sbi		eecr,eere			;Read Enable
		in		buferL,eedr			;read data
		sbrc	buferL,7
		sbr		buferL,0b01100000	; все числа до 31 и знак
		sbrs	buferL,7
		cbr		buferL,0b01100000	; все числа до 31 и знак
		st		Y+,buferL			;corrector
;-------- Установка начальных значений ---------------
		ldi		XL,0x3F
		ldi		XH,1
		ldi		temp,0x40
		st		X,temp				;pos of filter

		ldi		seconds,1
		ldi		setupcnt,0
		ldi		temp,bspeed
		mov		keycnt,temp
		clr		flags
		ldi		temp,0b01111111
		mov		razryad,temp
		ldi		temp, 175
		mov		timecnt,temp
		ldi		temp, 12
		mov		celscnt,temp			;3sec
		ldi		YH,0x01
		ldi		YL,0x10
		ldi		temp,0x0C			;-
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		ldi		temp,0x0A			;E
		st		Y+,temp
		ldi		temp,0x0B			;r
		st		Y+,temp
		st		Y+,temp
		rcall	conversion
		sei							;enable all interrupt
;------------------------------------------------------------
;refresh temperature
		cbr		flags,(1<<f_Tout)
		rcall	INITIALIZING
		rcall	REFRESH
		sbr		flags,(1<<f_Tout)
		rcall	INITIALIZING
		rcall	REFRESH

		clr		resmode				;сбросить watchdog режима настройки
;--------- Основной цикл -----------------------------
;
;___HHHHH__HHHHHH___HH____HHHHH__HHHHHH___
;__HH________HH____H__H___HH__HH___HH_____
;__HH________HH___HH__HH__HH__HH___HH_____
;___HHHH_____HH___HH__HH__HHHHH____HH_____
;______HH____HH___HHHHHH__HHHH_____HH_____
;______HH____HH___HH__HH__HH_HH____HH_____
;__HHHHH_____HH___HH__HH__HH__HH___HH_____
;
START:
		WDR
		sbrc	flags, f_TERMO
		rjmp	DS18B20Read
		sbrc	flags, f_TIME
		rjmp	TIMERead
		rjmp	START
DS18B20Read:
		rcall	INITIALIZING
		rcall	READDATA
		cbr		flags,(1<<f_TERMO)
		ldi		YH,0x01		
		ldi		YL,0x14
		sbrc	flags,f_I2CERR
		rjmp	Terror
		cbr		flags,(1<<f_less10)|(1<<f_Terr)
		ldd		temp,Y+(0x0E)	;0x122
		andi	temp,0x0F
		cpi		temp,0
		brne	notzero
		ldi		temp,0x0F		;' '
		sbrc	flags,f_minus
		ldi		temp,0x0C		;'-'
		cbr		flags,(1<<f_minus)
notzero:
		sbrs	flags,f_minus
		rjmp	notless10
		sbr		flags,(1<<f_less10)
		ldi		temp,0x0C		;'-'
		st		Y,temp
		ldd		temp,Y+(0x0E)	;0x122
		adiw	Y,1
		st		Y+,temp
		ldd		temp,Y+(0x0D)	;0x123
		st		Y+,temp
		rjmp	DisplayT
notless10:
		st		Y+,temp
		ldd		temp,Y+(0x0E)	;0x123
		st		Y+,temp
		ldd		temp,Y+(0x0E)	;0x124
		st		Y+,temp
		rjmp	DisplayT
Terror:
		sbrs	flags,f_Terr
		rjmp	TRYanother
		ldi		temp,0x0A		;'E'
		st		Y+,temp
		ldi		temp,0x0B		;'r'
		st		Y+,temp
		st		Y+,temp
		ldi		temp,(1<<f_Tout)
		eor		flags,temp
		rjmp	DisplayT
TRYanother:
		sbr		flags,(1<<f_TERMO)|(1<<f_Terr)
		rjmp	RefreshT
DisplayT:
		sbrc	flags,f_Tout
		sbr		flags2,(1<<f_ToIND)
		sbrs	flags,f_Tout
		cbr		flags2,(1<<f_ToIND)
		rcall	conversion
RefreshT:
		rcall	INITIALIZING
		rcall	REFRESH
		ldi		temp,(1<<f_Tout)
		eor		flags,temp

		rcall	INITIALIZING
		rcall	REFRESH
		rjmp	START
;---------------------------------------------------------------
TIMERead:
		cbr		flags,(1<<f_TIME)
; test in setup mode
		tst		setupcnt
		breq	PC+2
		rjmp	SETUP

		sbr		flags2,(1<<f_PCF)
		rcall	I2C_SETADRES
		rcall	I2C_READ
		sbrs	flags,f_I2CERR
		rjmp	timegood
		cbr		flags2,(1<<f_PCF)
		rcall	I2C_SETADRES
		rcall	I2C_READ
		ldi		YH,1		
		sbrs	flags,f_I2CERR
		rjmp	DS2PCF
;if I2C error display '--:--'
		ldi		YL,0x10
		ldi		temp,0x0C			;'-'
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		rcall	conversion
		rjmp	START
DS2PCF:
		ldi		YL,RAM_PCF+5
		ld		temp,-Y							;day
		std		Y+1,temp
		ld		temp,-Y							;dow
		std		Y+3,temp
		ld		temp,-Y							;hour
		std		Y+2,temp
		ld		temp,-Y							;min
		std		Y+2,temp
		ld		temp,-Y							;sec
		std		Y+2,temp
timegood:
		ldi		YL,$02
		ld		buferL,Y+			;sec
		ldd		buferH,Y+(0x27-0x03);oldsec
		cp		buferH,buferL
		brne	PC+2
		rjmp	endofcorrect		;endofsec
		std		Y+(0x27-0x03),buferL;newsec

;convert seconds BCD to dec
		mov		buferH,buferL
		swap	buferH
		andi	buferH,0x07			;most of second
		ldi		temp,6
		mul		buferH,temp
		sub		buferL,R0			;dec = BCD-high(bcd)*6
		inc		buferL
		mov		seconds,buferL
;minutes
		ldi		YL,$03		
		ld		buferL,Y+			;min
;convert dec to bin
		mov		buferH,buferL
		swap	buferH
		andi	buferH,0x0F			;most
		ldi		temp,6
		mul		buferH,temp
		sub		buferL,R0			;buferL= converted min
		mov		minutes,buferL
endofsec:
;for correction
		ldi		YL,$030
		ld		temp,Y				;corrector
		cpi		temp,0
		breq	endofcorrect
		sbrs	temp,7
		rjmp	positive
		com		temp
		inc		temp
positive:
		ldi		YL,$04
		ld		buferH,Y			;hr
		andi	buferH,0x3F
		cpi		temp,8
		brmi	less8
		cpi		temp,15
		brmi	less15
		cpi		temp,22
		brmi	less22


		cpi		buferH,0x05
		breq	check59
		subi	temp,7
less22:
		cpi		buferH,0x17
		breq	check59
		subi	temp,7
less15:
		cpi		buferH,0x11
		breq	check59
		subi	temp,7
less8:
		ldi		YL,$06
		ld		buferL,Y			;dow
		cp		buferL,temp
		brpl	endofcorrect		;dow>correctinweek goto end
		cpi		buferH,0x23
		breq	check59
		rjmp	endofcorrect
check59:
		ldi		YL,$03		
		ld		buferL,Y			;min
		andi	buferL,0x7F
		cpi		buferL,0x59
		brne	endofcorrect
		ldi		YL,$030
		ld		temp,Y				;corrector
		ldi		YL,$02		
		ld		buferL,Y			;sec
		andi	buferL,0x7F
		cpi		buferL,0x04
		brne	check6
		sbr		flags2,(1<<f_correct)
check6:
		sbrs	flags2,f_correct
		rjmp	endofcorrect
		cpi		buferL,0x06
		brne	endofcorrect
		cbr		flags2,(1<<f_correct)
		sbrs	temp,7
		inc		buferL
		sbrc	temp,7
		dec		buferL
		st		Y,buferL			;sec
		rcall	I2C_SETADRES
		rcall	I2C_WRITE
endofcorrect:		
;testVLflag:
		ldi		temp,(1<<f_VL)
		eor		flags,temp			;for blinking?
		sbrs	flags,f_VL
		rjmp	VL_Good
		ldi		YL,2		;seconds		
		ld		temp,Y
		sbrs	temp,7		;VL=0 time is guaranteed
		rjmp	VL_Good
		ldi		YL,0x10
		ldi		temp,0x0E	;_
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp
		rcall	conversion
		rjmp	START
VL_Good:
		ldi		YL,$03		
		ld		buferL,Y+			;min
		mov		buferH,buferL
		andi	buferL,0x0F
		swap	buferH
		andi	buferH,0x07
		std		Y+($13-$04),buferL	;ед. минут
		std		Y+($12-$04),buferH	;дес. минут
		ld		buferL,Y+			;hour
		mov		buferH,buferL
		andi	buferL,0x0F
		swap	buferH
		andi	buferH,0x03
		brne	PC+2
		ldi		buferH,0x0F
		std		Y+($11-$05),buferL	;ед. часов
		std		Y+($10-$05),buferH	;дес. часов		
		rcall	conversion
		rjmp	START
SETUP:
;разместить в байтах data to display полубайты из:
;в режиме
;1,2		0x104 0x103 h:m
;3			__    0x106 day of week
;4			I2C_write

;clear all
		ldi		YH,1
		ldi		YL,0x10
		ldi		buferL,0x0F
		st		Y+,buferL			;дес. часов
		st		Y+,buferL			;ед. часов
		st		Y+,buferL			;дес. минут
		st		Y+,buferL			;ед. минут
	
		cpi		setupcnt,1
		breq	mode12	
		cpi		setupcnt,2
		brne	cpimode3
mode12:
		ldi		YL,$03		
		ld		buferL,Y+			;min
		mov		buferH,buferL
		andi	buferL,0x0F
		swap	buferH
		andi	buferH,0x07
		std		Y+($13-$04),buferL	;ед. минут
		std		Y+($12-$04),buferH	;дес. минут
		ld		buferL,Y+			;hour
		mov		buferH,buferL
		andi	buferL,0x0F
		swap	buferH
		andi	buferH,0x03
		brne	PC+2
		ldi		buferH,0x0F
		std		Y+($11-$05),buferL	;ед. часов
		std		Y+($10-$05),buferH	;дес. часов		
;		rjmp	blinking
;mode34:
;blinking:
		ldi		buferL,bspeed
		cp		buferL,keycnt
		breq	PC+2
		rjmp	endblinking
		sbrs	celscnt,0
		rjmp	endblinking
		ldi		buferL,0x0F
		ldi		YL,0x10				; часы
		sbrc	setupcnt,0			;temp=setupcnt
		ldi		YL,0x12				; минуты
		st		Y+,buferL
		st		Y,buferL
		rjmp	endblinking
cpimode3:	
		cpi		setupcnt,3
		brne	cpimode4
		ldi		YL,$30		
		ld		buferL,Y			;correct sec per week
		ldi		YL,$10
		ldi		temp,0x0D			;C  (C0rrECt)
		st		Y+,temp

		ldi		temp,0x0F
		sbrs	buferL,7
		rjmp	label2
		com		buferL
		inc		buferL
		ldi		temp,0x0C			;-
label2:
		st		Y+,temp

		andi	buferL,0x1F			;no sign
		clr		buferH
convHEX2DEC:
		inc		buferH
		subi	buferL,10
		brcc	convHEX2DEC
		dec		buferH
		subi	buferL,-10
				
		st		Y+,buferH
		st		Y+,buferL	
		rjmp	endblinking
cpimode4:
		cpi		setupcnt,4
		brne	endsetup
;mode4 
		ldi		temp,0				;EEPROM adress
		ldi		YL,0x30				;corrector
;writeEEPROM
		ld		buferL,Y+		
		out		eedr,buferL
		out		eearl,temp
		cli							;disable all interrupt
		sbi		eecr,eemwe			;Master Write Enable
		sbi		eecr,eewe			;Write Enable
		sei							;enable all interrupt
WaitWriteComplite:
		sbic	eecr,eewe			;WaitWriteComplite
		rjmp	WaitWriteComplite
;сбросить секунды, и записать 
		ldi		YL,RAM_PCF
		ldi		temp,0
		st		Y+,temp
		st		Y+,temp
		st		Y+,temp					;sec=00
		ldi		YL,RAM_PCF+0x05
		ldi		temp,1					;day
		st		Y+,temp
		ld		temp,Y					;dow
		andi	temp,0x07
		st		Y+,temp
		ldi		temp,1
		st		Y+,temp					;month
		st		Y+,temp					;year
		ldi		YL,RAM_PCF+0x0D
		ldi		temp,0x80				;CLKOUT=32768
		st		Y+,temp
;correct pcf\ds
		sbrc	flags2,f_PCF
		rjmp	endpcf2ds

		ldi		YL,RAM_PCF
		ldd		temp,Y+2					;sec
		st		Y+,temp
		ldd		temp,Y+2					;min
		st		Y+,temp
		ldd		temp,Y+2					;hour
		st		Y+,temp
		ldd		temp,Y+3					;dow
		st		Y+,temp
		ldd		temp,Y+1					;day
		st		Y+,temp
endpcf2ds:		
		
		rcall	I2C_SETADRES
		rcall	I2C_WRITE
		sbrs	flags,f_I2CERR
		clr		setupcnt
		sbr		flags,(1<<f_time)
		ldi		temp, 48
		mov		celscnt,temp
endblinking:
		rcall	conversion
endsetup:
		rjmp	Start

;*****************************************************
;*--------- Прерывание ------------------------------*
;*****************************************************
COMPA:								;every 1,428ms
		push	temp
		in		temp,SREG
		push	temp
		push	buferL
		push	buferH

; сменить разряды и сегменты 
		in		temp,R_PORT				;\
		ori		temp,0b11111110			; \
		out		R_PORT,temp				;  } hide pixels
		ser		temp					; /
		out		S_PORT,temp				;/
		sec		
		ror		razryad
		sbrs	razryad,0
		ldi		razryad,0b01111111

		in		temp,R_PORT				;\
		ori		temp,0b11111110			; \
		and		temp,razryad			;  } new razr
		out		R_PORT,temp				; /


;send seconds to register
		sbrc	razryad,7
		rjmp	endofsend
		cpi		setupcnt,0
		brne	endofsend
		mov		temp,seconds
		ldi		buferL,61
		sub		buferL,temp
		ldi		XH,1




		rjmp	oneLED

		ldi		XL,0x03					;min
		ld		buferH,X
		sbrs	buferH,0				;odd min inverse seconds
		rjmp	clk60to0sec
clk0to60sec:		
		cbi		PortS,DatPin		;Data0
clk0to60L:		
		cbi		PortS,ClkPin		;Clock
		dec		buferL
		sbi		PortS,ClkPin		;Clock
		brne	clk0to60L
		sbi		PortS,DatPin		;Data1
clk0to60H:		
		cbi		PortS,ClkPin		;Clock
		dec		temp
		sbi		PortS,ClkPin		;Clock
		brne	clk0to60H
		rjmp	endofclk
clk60to0sec:
		sbi		PortS,DatPin		;Data1
clk60to0H:		
		cbi		PortS,ClkPin		;Clock
		dec		buferL
		sbi		PortS,ClkPin		;Clock
		brne	clk60to0H
		cbi		PortS,DatPin		;Data0
clk60to0L:		
		cbi		PortS,ClkPin		;Clock
		dec		temp
		sbi		PortS,ClkPin		;Clock
		brne	clk60to0L

		rjmp	endofclk
		
oneLED:
		cbi		PortS,ClkPin		;Clock
		subi	temp,1
		sbi		PortS,DatPin		;Data1
		breq	PC+2
		cbi		PortS,DatPin		;Data0
		dec		buferL
		sbi		PortS,ClkPin		;Clock
		brne	oneLED
endofclk:
		cbi		PortS,ClkPin		;Clock
		cbi		PortS,DatPin		;Data
endofsend:
;clear seconds write min (razryad bit 7>..>1)
;		mov		temp,razryad
;		ror		temp
;		sbrc	razryad,4
;		rjmp	endofclr

		ldi		XL,0x3E
		ld		buferH,X			;min 8-44 max
		cpi		buferH,44
		brpl	endofclr
		ldi		temp,0b11111101
		cpi		buferH,36
		brpl	cpirazryad
		ldi		temp,0b11111011
		cpi		buferH,28
		brpl	cpirazryad
		ldi		temp,0b11110111
		cpi		buferH,20
		brpl	cpirazryad
		ldi		temp,0b11101111
		cpi		buferH,12
		brpl	cpirazryad
		ldi		temp,0b11011111
cpirazryad:
		cp		razryad,temp
		brne	endofclr
		ldi		temp,60
		cpi		setupcnt,0
		breq	PC+2
		mov		temp,minutes
		ldi		buferL,59
clr60sec:		
		cbi		PortS,ClkPin		;Clock
		sbi		PortS,DatPin		;Data
		cpse	temp,buferL
		cbi		PortS,DatPin		;Data
		subi	buferL,1
		sbi		PortS,ClkPin		;Clock
		brpl	clr60sec
		cbi		PortS,ClkPin		;Clock
		cbi		PortS,DatPin		;Data
endofclr:


; refresh time
		dec		timecnt
		brne	cntend
		ldi		temp, 175				;1,428ms*175
		mov		timecnt,temp
		sbr		flags,(1<<f_TIME)		;0,25s
		sbi		ADCSRA,ADSC				;ADC Start Conversion
; refresh temperature
		dec		celscnt
		brne	resmodecnt
		ldi		temp, PeriodTermo*4		;1sec=4time
		mov		celscnt,temp
		sbr		flags,(1<<f_TERMO)
resmodecnt:
		cpi		setupcnt,0
		breq	cntend
		ldi		temp,100				;25 sec
		inc		resmode
		cp		resmode,temp
		brne	cntend
		clr		setupcnt
		clr		resmode
cntend:
		ldi		XH,1
		sbrs	razryad,1
		ldi		XL,$1C					;in
		sbrs	razryad,2
		ldi		XL,$1E					;out
		sbrs	razryad,3
		ldi		XL,$1B
		sbrs	razryad,4
		ldi		XL,$1A					;dpoint
		sbrs	razryad,5
		ldi		XL,$1D					;point
		sbrs	razryad,6
		ldi		XL,$18
		sbrs	razryad,7
		ldi		XL,$19
		ld		temp,X
		out		S_PORT,temp				;new segments


;----- проверка кнопок -------------------
		sbrs	razryad,notbutt
		rjmp	RAZR_NO
		sbic	K_Port-2,keypin
		rjmp 	endbutton 
		ldi 	temp,bspeed 
		cp 		keycnt,temp
		brne	PC+2 
		dec		keycnt 			;первый запуск
		subi	temp,2
		cpse	keycnt,temp
		rjmp	endbutton
;button is pressed 

;RAZR_MODE:
		sbrc	razryad,modebutt
		rjmp	RAZR2
;setup button 
		clr		resmode				;сбросить watchdog режима настройки
		sbr		flags,(1<<f_time)
		inc		setupcnt
		ldi		temp,5				;when setupcnt=4 do rcall I2Cwrite & setupcnt+1
		cp		setupcnt,temp
		brne	PC+2
		clr		setupcnt 
		rjmp	endbutton
RAZR2:
		sbrc	razryad,upbutt		;UP button 
		rjmp	RAZR3
		ldi		XH,1
		ldi		buferH,6
		mov		buferL,setupcnt 
		cpi		buferL ,1
		brne	compare2
		ldi		XL,3		;min
		ldi		temp,0		;<-
		push	temp		;  |
		ldi		temp,0x59	;_/
		rjmp	UP_
compare2:
		cpi		buferL ,2
		brne	compare3
		ldi		XL,4		;hour
		ldi		temp,0		;<-
		push	temp		;  |
		ldi		temp,0x23	;_/
		rjmp	UP_
compare3:
		cpi		buferL ,3
		brne	compare3x
		ldi		XL,0x30		;correct
		clr		resmode		;сбросить watchdog режима настройки
		ld		buferL,X
		sbrc	buferL,7
		sbr		buferL,0b01100000	; все числа до 31 и знак
		sbrs	buferL,7
		cbr		buferL,0b01100000	; все числа до 31 и знак

		inc		buferL
		cpi		buferL,29	;_
		brlt	PC+2		; \
		ldi		buferL,28	;<-
		rjmp	compend
compare3x:
		cpi		buferL ,5
		brne	compare4
		ldi		XL,6		;weekdays
		ldi		temp,1		;<-
		push	temp		;  |
		ldi		temp,0x7	;_/
		rjmp	UP_
compare4:
		cpi		buferL ,6
		breq	PC+2
		rjmp	endbutton 
		ldi		XL,5		;days
		ldi		temp,1		;<-
		push	temp		;  |
		ldi		temp,0x31	;_/
;		rjmp	UP_
;compare5:
;		cpi		buferL ,7
;		brne	compare6
;		ldi		XL,7		;months
;		ldi		temp,1		;<-
;		push	temp		;  | century bit=0 is 20xx
;		ldi		temp,0x12	;_/
;		rjmp	UP_
;compare6:
;		cpi		buferL ,8
;		breq	PC+2
;		rjmp	endbutton 
;		ldi		XL,8		;year
;		ldi		temp,0x10	;<-
;		push	temp		;  |
;		ldi		temp,0x79	;_/
UP_:	
		clr		resmode		;сбросить watchdog режима настройки
		ld		buferL,X
		cbr		buferL,(1<<7)		; все числа до 79 BCD
		inc		buferL
		add		buferL,buferH 		;+6
		brhs	PC+2
		sub 	buferL,buferH		;небыло переноса полубайта
		cp		temp,buferL
		pop		temp
		brsh	compend
		mov		buferL,temp
		rjmp	compend
RAZR3:
		sbrc	razryad,downbutt	;DOWN button 
		rjmp	endbutton
		ldi		XH,1
		mov		buferL,setupcnt 
		cpi		buferL ,1
		brne	compare7
		ldi		XL,3		;min
		ldi		temp,0x59	;<-
		push	temp		;  |
		ldi		temp,0x00	;_/
		rjmp	DOWN_
compare7:
		cpi		buferL ,2
		brne	compare8
		ldi		XL,4		;hour
		ldi		temp,0x23	;<-
		push	temp		;  |
		ldi		temp,0x00	;_/
		rjmp	DOWN_
compare8:
		cpi		buferL ,3
		brne	compare8x
		ldi		XL,0x30		;correct
		clr		resmode		;сбросить watchdog режима настройки
		ld		buferL,X
		sbrc	buferL,7
		sbr		buferL,0b01100000	; все числа до 31 и знак
		sbrs	buferL,7
		cbr		buferL,0b01100000	; все числа до 31 и знак

		dec		buferL
		cpi		buferL,-28	;_
		brge	PC+2		; \
		ldi		buferL,-28	;<-
		rjmp	compend
compare8x:
		cpi		buferL ,5
		brne	endbutton
		ldi		XL,5		;day
		ldi		temp,0x31	;<-
		push	temp		;  |
		ldi		temp,0x01	;_/
;		rjmp	DOWN_
;compare9:
;		cpi		buferL ,6
;		brne	compare10
;		ldi		XL,7		;month
;		ldi		temp,0x12	;<-
;		push	temp		;  |
;		ldi		temp,0x01	;_/
;		rjmp	DOWN_
;compare10:
;		cpi		buferL ,7
;		brne	endbutton
;		ldi		XL,8		;year
;		ldi		temp,0x79	;<-
;		push	temp		;  |
;		ldi		temp,0x10	;_/
DOWN_:
		clr		resmode				;сбросить watchdog режима настройки
		ld		buferL,X
		cbr		buferL,(1<<7)		; все числа до 79BCD
		subi	buferL,1
		brhc	PC+2
		subi	buferL,6
		cp		buferL,temp
		pop		temp
		brpl	compend
		mov		buferL,temp
compend:
		st		X,buferL 
		sbr		flags,(1<<f_time)
; recalc minutes
		cpi		buferH,3
		brne	minhour
		subi	buferL,-30
		mov		minutes,buferL
		rjmp	endbutton
minhour:
		mov		buferH,buferL
		swap	buferH
		andi	buferH,0x0F			;most
		ldi		temp,6
		mul		buferH,temp
		sub		buferL,R0			;buferL= converted min or hour
		mov		buferH,setupcnt
		cpi		buferH,2
		brne	label1				;my fantasy end when time is 23:53
		subi	buferL,12
		brpl	PC+2
		subi	buferL,-12
		ldi		temp,5
		mul		temp,buferL
		mov		buferL,R0
label1:		 
		mov		minutes,buferL
;end
		rjmp	endbutton
RAZR_NO:
		ldi		temp,bspeed
		cp		temp,keycnt
		breq	endbutton
		dec		keycnt
		brne	endbutton
		mov		keycnt,temp
endbutton:
;----- проверка кнопок end -------------------

;endcompa
		pop		buferH
		pop		buferL
		pop		temp
		out		SREG,temp
		pop		temp
		reti						;закончить прерывание
;----------------------------------------------------
;   Очистка
;----------------------------------------------------
COMPB:
		push	temp
		in		temp,SREG
		push	temp

		in		temp,R_PORT				;\
		ori		temp,0b11111110			; \
		out		R_PORT,temp				;  } hide pixels
		ser		temp					; /
		out		S_PORT,temp				;/

		pop		temp
		out		SREG,temp
		pop		temp
		reti						;закончить прерывание

ADCCC:
		push	temp
		in		temp,SREG
		push	temp
		push	buferL
		push	buferH
		push	XL
		push	XH

		ldi		XL,0x3F
		ldi		XH,1
		ld		temp,X
		subi	temp,-2
		cpi		temp,0x60
		brlo	PC+2
		ldi		temp,0x40
		st		X,temp
		mov		XL,temp			;set next position
		in		temp,ADCL				
		st		X+,temp
		in		temp,ADCH				
		st		X,temp			;added one new elem to array

		ldi		XL,0x40			;set position to begin
		ser		buferH
		ser		buferL
calcsum:
		ld		temp,X+
		sub		buferL,temp
		ld		temp,X+
		sbc		buferH,temp
		cpi		XL,0x60
		brne	calcsum
		lsl		buferL
		rol		buferH
		lsl		buferL
		rol		buferH			;max 155 - 110 min
		cpi		buferH,235
		brlo	PC+2
		ldi		buferH,235		; =< 235
		subi	buferH,110
		brpl	PC+3
		clr		buferH
		clr		buferL
		subi	buferH,-8		;2048	min
		out		OCR1BH,buferH	;11428 max bright
		out		OCR1BL,buferL
		ldi		XL,0x3E
		st		X,buferH		;min 8-44 max

		pop		XH
		pop		XL
		pop		buferH
		pop		buferL
		pop		temp
		out		SREG,temp
		pop		temp
		reti						;закончить прерывание
