; Find Constant  By PEK  ´2000
;
; This program was created to be used
; with the anemometer-program. The
; function of the code is to find
; the right constant in a list of
; many constants and then find new
; constants which are related to the
; first one.
; In this program the real temperature
; measured with a thermometer is :
; tempen + (tempen+1)*(tempen+2)


.include "8515def.inc"


; ************************************
; * Variable Definitions             
; ************************************
.def	temp	=R16
.def	varv	=R17
.def	addvalue=R18


; ************************************
; * SRAM Allocations
; ************************************
.dseg
data:	.BYTE	2
tempen:	.BYTE	3


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0

start:
	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp


	ldi	ZL,low(bitr47*2+14)	; Z point at last bit-constant of the first resistor
	ldi	ZH,high(bitr47*2+14)

	ldi	addvalue,0


; * Y = Datavärden från 4,7k... spara undan i SRAM åxå
	lds	YL,data
	lds	YH,data+1



	lpm				; Test if we want to use the first resistor or not
	adiw	ZL,1
	sub	YL,R0
	lpm
	sbc	YH,R0
	brcc	Start_Find_Constant


; * Mät med 27k resistor och spara undan i SRAM
	ldi	addvalue,8


Start_Find_Constant:
	ldi	varv,0
	ldi	ZL,low(bitr47*2)	; Z point at first constant to compare with
	ldi	ZH,high(bitr47*2)
	add	ZL,addvalue
	add	ZL,addvalue
	clr	temp
	adc	ZH,temp

New_Constant:
	lds	YL,data			; Y = Data value
	lds	YH,data+1

	lpm				; Lower Constant and subtract
	adiw	ZL,1
	sub	YL,R0
	lpm				; Higher Constant and subtract with Carry
	sbc	YH,R0
	brcc	Found_Constant

	inc	varv
	adiw	ZL,1
	rjmp	New_Constant

Found_Constant: 
	sts	tempen+2,YL		; Store number of "to many" bits

	add	addvalue,varv

	ldi	ZL,low(T47bit*2)	; Z point at right temp/bit constant
	ldi	ZH,high(T47bit*2)	
	add	ZL,addvalue
	clr	temp
	adc	ZH,temp
	lpm
	sts	tempen+1,R0		; Store "temp constant" to multiply with "to many" bits

	ldi	ZL,low(temp47*2)	; Z point at temperature to add
	ldi	ZH,high(temp47*2)
	add	ZL,addvalue
	clr	temp
	adc	ZH,temp
	lpm
	sts	tempen,R0		; Store "temperature to add"

					; The real temperature is now :
					; to_many * tempbit + tempadd

loop:
	rjmp	loop


; ************************************
; * Constant Definitions in Flash
; ************************************
.cseg
T47bit:	.DB	128,122,116,114,109,111,114,119				; Start with High values
T27bit:	.DB	122,109,98,93,88,88,91,96,106,119,143,167,217,217
bitr47:	.DW	672,631,588,544,498,453,409,367
bitr27:	.DW	738,692,641,587,530,473,418,366,319,277,242,212,189,0
temp47:	.DB	55,50,45,40,35,30,25,20
temp27:	.DB	20,15,10,5,0,-5,-10,-15,-20,-25,-30,-35,-40,-60