Code: Select all
from utime import sleep_ms, sleep_us
from machine import Pin
from time import sleep
#based of DS1820
#https://iopress.info/index.php/books/programming-the-raspberry-pi-pico-in-micropython/9-programs/55-picopythonprograms
#Page 245
class MAX31850:
def __init__(self, pin):
self.pin = Pin(pin, mode=Pin.IN)
self.pin.high()
def presence(self): #initialization handshake
self.pin.init(mode=Pin.OUT)
self.pin.high()
sleep_ms(1)
self.pin.low()
sleep_us(480)
self.pin.init(mode=Pin.IN)
sleep_us(70)
b = self.pin.value()
sleep_us(410)
return b
@micropython.native #writing bits
def writeBit(self, b):
if b == 1:
delay1 = 1
delay2 = 30
else:
delay1 = 30
delay2 = 0
self.pin.low()
for i in range(delay1):
pass
self.pin.high()
for i in range(delay2):
pass
def writeByte(self, byte): #will write the low eight bits of an int to the device
self.pin.init(mode=Pin.OUT)
for i in range(8):
self.writeBit(byte & 1)
byte = byte >> 1
self.pin.init(mode=Pin.IN)
@micropython.native #reading bits
def readBit(self):
self.pin.init(mode=Pin.OUT)
self.pin.low()
self.pin.high()
self.pin.init(mode=Pin.IN)
b = self.pin.value()
sleep_us(60)
return b
def readByte(self): #make a byte
byte = 0
for i in range(8):
byte = byte | self.readBit() << i
return byte
def convert(self): #start conversion
self.writeByte(0x44)
for i in range(500):
sleep_ms(10)
if self.readBit() == 1:
j = i
break
return j
def crc8(self, data, len): #cyclic redundancy checksum
crc = 0
for i in range(len):
databyte = data[i]
for j in range(8):
temp = (crc ^ databyte) & 0x01
crc >>= 1
if temp:
crc ^= 0x8C
databyte >>= 1
return crc
def getTemp(self):
if self.presence() == 1:
return -1000 #no device
self.writeByte(0xCC)
if self.convert() == 500:
return -3000 #device faild to provide data
self.presence()
self.writeByte(0xCC) #skip ROM read
self.writeByte(0xBE) #read scratchpad
data = []
for i in range(9):
data.append(self.readByte())
if self.crc8(data, 9) != 0:
return -2000 #crc error
t1 = data[0]
t2 = data[1]
#t2 = 0b000001 #test data from the datasheet positive temp no fault bits
#t1 = 0b10010011 #in the real life the last two lsb are fault detect
#t2 = 0b111100 #test data from the datasheet negative temp no fault bits
#t1 = 0b00011000 #in the real life the last two lsb are fault detect
t2 = t2 << 8 #shift rigft the MSB
temp1 = t2 | t1 #conbine MSB and LSB of the K type
temp1 = temp1 >> 2 #remove fault detection, comment when using test data
print("{:8b}".format(t2))
print("{:8b}".format(t1))
print("{:16b}".format(temp1))
if (temp1 >> 13 != 1): #check to see if not a negative number
temp1 = temp1 * 0.25
print("here i am")
else:
temp1 = temp1 - 0b100000000000000 #remove the sign bit
temp1 = temp1 * 0.25
return temp1
max31850 = MAX31850(15)
while True:
if max31850.presence() == 1:
print("No device")
else:
print("Device present")
print(max31850.getTemp())
sleep_ms(750)
Cheers!