;Correct.spt SPice20212 demo/calibration with nonlinearity correction using MMi200 with LCD
;The nonlinearity correction is applied only
;to the first channel, to allow comparisons to be made.

;RAM storage
Temp		EQU		20

;Use for MS12 only		ON		20	;MS12 backlight

;Initialize the SPice connector for 3 analog inputs
		SetU		0,3
		SetU		1,3
		SetU		2,3
		SPiceConfigU

;Main program loop:

Loop:
;This section displays the raw analog readings on the
;top line of the display. Full scale is always 255 counts

		AnInE			;Use AnInC on MS12
		OBLCD_SetCur	0,0
		OBLCD_UDecDispXFW

		AnInF			;Use AnInD on MS12
		OBLCD_SetCur	0,6
		OBLCD_UDecDispXFW

		AnInG			;Use AnInE on MS12
		OBLCD_SetCur	0,12
		OBLCD_UDecDispXFW

;This section displays the readings as voltages.

;For phase A the conversion is done using a correction algorithm
;based on a polynomial function. 

;For the other two phases the conversion is a simple scaling.
;The scale factor initially loaded into Q will determine the
;full scale range, i.e. the voltage corresponding to 255
;raw counts.

		AnInE			;Use AnInC on MS12
		GoSub		Correct
		OBLCD_SetCur	1,0
		OBLCD_UDecDispXFW

;The scale factor for the other two readings
;is Vfs/255, where Vfs is the required full scale voltage.

		fLoadQ		1.0	;1.0  for FS=255V (240V+10%)
					;0.5176 for FS=132V (120V+10%)

		AnInF			;Use AnInD on MS12
		OBLCD_SetCur	1,6
		Float
		fMul
		OBLCD_fDispW	3,0

		AnInG			;Use AnInE on MS12
		OBLCD_SetCur	1,12
		Float
		fMul
		OBLCD_fDispW	3,0



		GoTo		Loop


;Correct for nonlinearity

;Implements the function 

;y = 2.859320E-06 x^3 -1.011672E-03 x^2 +1.058639E+00x +3.916506E+00

;These particular coefficients were determined with a specific transformer,
;with the system calibrated for 255V full scale. A different transformer
;and/or full scale range will require different coefficients.

Correct:
		Float
		fStore		Temp
		fLoadQ		2.859320E-06		; X^3 coefficient
		fMul
		fLoadQ		-1.011672E-03		; X^2 coefficient
		fAdd
		fRecallQ	Temp
		fMul
		fLoadQ		+1.058639E+00		; X^1 coefficient
		fAdd
		fRecallQ	Temp
		fMul
		fLoadQ		+3.916506E+00		; constant offset
		fAdd
		fLoadQ		0.5			;Rounding
		fAdd
		Fix
		Return