89 lines
2.5 KiB
Python
89 lines
2.5 KiB
Python
import machine
|
|
|
|
class TMP117:
|
|
RESOLUTION = 0.0078125
|
|
|
|
TEMP_ADDR = 0x00
|
|
CONFIG_ADDR = 0x01
|
|
NIST_ADDR = 0x05
|
|
|
|
TEMP_SIZE = 16
|
|
|
|
CONFIG_REGISTER_MAP = {
|
|
"HIGH_Alert": 15,
|
|
"LOW_Alert": 14,
|
|
"Data_Ready": 13,
|
|
"EEPROM_Busy": 12,
|
|
"MOD1": 11,
|
|
"MOD0": 10,
|
|
"CONV2": 9,
|
|
"CONV1": 8,
|
|
"CONV0": 7,
|
|
"AVG1": 6,
|
|
"AVG0": 5,
|
|
"T/nA": 4,
|
|
"POL": 3,
|
|
"DR/Alert": 2,
|
|
"Soft_Reset": 1,
|
|
"--": 0
|
|
}
|
|
|
|
def __init__(
|
|
self,
|
|
name: str,
|
|
i2c: machine.I2C|machine.SoftI2C,
|
|
i2c_addr: int = 72,
|
|
config_int: int = 544):
|
|
self.name = name
|
|
self.i2c_addr = i2c_addr
|
|
self.i2c = i2c
|
|
|
|
self.NIST_ID = int.from_bytes(self.i2c.readfrom_mem(self.i2c_addr, self.NIST_ADDR, 2), "big")
|
|
# Set configuration
|
|
self.write_configuration_integer(config_int)
|
|
|
|
def bytes_to_temperature(self, binary:bytes):
|
|
"""Converts a 2's complement 16 bit value to the appropriate temperature value."""
|
|
val = int.from_bytes(binary, "big")
|
|
if (val & (1 << (self.TEMP_SIZE - 1))) != 0:
|
|
val = val - (1 << self.TEMP_SIZE)
|
|
|
|
return val * TMP117.RESOLUTION
|
|
|
|
def int_to_config_dict(self, integer:int):
|
|
"""Converts a configuration """
|
|
assert integer < 2**(16)
|
|
bits = list(f"{integer:016b}")
|
|
bits.reverse()
|
|
|
|
result = {}
|
|
for key in self.CONFIG_REGISTER_MAP.keys():
|
|
result[key] = bits[self.CONFIG_REGISTER_MAP[key]]
|
|
|
|
return result
|
|
|
|
def config_dict_to_int(self, config_dict):
|
|
array = [None for _ in range(16)]
|
|
|
|
for option in config_dict.keys():
|
|
array[self.CONFIG_REGISTER_MAP[option]] = config_dict[option]
|
|
|
|
array.reverse()
|
|
bit_string = ""
|
|
for bit in array:
|
|
bit_string += str(bit)
|
|
write_byte = int(bit_string, 2)
|
|
|
|
def write_configuration_integer(self, config_int:int):
|
|
write_byte = config_int.to_bytes(2, "big")
|
|
self.i2c.writeto_mem(self.i2c_addr, self.CONFIG_ADDR, write_byte)
|
|
|
|
def read_configuration_integer(self):
|
|
binary = self.i2c.readfrom_mem(self.i2c_addr, self.CONFIG_ADDR, 2)
|
|
integer = int.from_bytes(binary, "big")
|
|
return integer
|
|
|
|
def read_temperature(self):
|
|
binary = self.i2c.readfrom_mem(self.i2c_addr, self.TEMP_ADDR, 2)
|
|
return self.bytes_to_temperature(binary)
|