#!/usr/bin/python

import spidev
import time
import os
 
# Open SPI bus
spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz=100000
spi.mode = 0b01

def read_reg(addr):
	reg = spi.xfer([addr, 0xFF]);

	return reg[1]
	
def write_reg(addr, data):
	spi.xfer([addr+0x80, data]);

def read_digits():
	msb = read_reg(0x01)
	lsb = read_reg(0x02)
	digits = float(256*msb + lsb)/2

	return digits

def calc_R(Rref, digits):
	k = digits / 8192 / 4
	R = k*Rref

	return R

def vanDusenLut (R0, Tmin, Tmax, dT):
	a = +3.90830e-03;
	b = -5.77500e-07;
	c = -4.18301e-12;

	Rv = []
	Tv = []
	T = Tmin
	while T <= Tmax:
		R = R0*(1 + a*T + b*T**2)

		if T < 0.0:
			R += R0*c*(T - 100)*T**3;
		
		Rv.append(R)
		Tv.append(T)
		T += dT

	return Rv, Tv

def vanDusen_temp(Rmeas):
	RLut, TLut = vanDusenLut(100, -150, +500, 1.0)

	# Find candidate
	i = 0
	for R in RLut:
		if R > Rmeas:
			break
		i += 1

	# Linear interpolation
	R0 = RLut[i-1]
	R1 = RLut[i]
	T0 = TLut[i-1]
	T1 = TLut[i]

	dR = R1 - R0
	dT = T1 - T0

	k = (Rmeas-R0)/dR
	T = T0 + dT*k

	return T

# Main
write_reg(0x00, 0xA3)
digits = read_digits()
R = calc_R(430, digits)
T = vanDusen_temp(R)
print("R={:.3f} Ohm, T={:.2f} degC".format(R, T))

for i in range (0, 8):
	print("Reg[0x{}]: 0x{:02X}".format(i, read_reg(i)))

print("End of program")

