A repository for MicroPython code that communicates with and relays information from the Texas Instruments TMP117/119 temperature sensor.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.4 KiB

2 months ago
  1. import machine
  2. class TMP117:
  3. RESOLUTION = 0.0078125
  4. TEMP_ADDR = 0x00
  5. CONFIG_ADDR = 0x01
  6. NIST_ADDR = 0x05
  7. TEMP_SIZE = 16
  8. CONFIG_REGISTER_MAP = {
  9. "HIGH_Alert": 15,
  10. "LOW_Alert": 14,
  11. "Data_Ready": 13,
  12. "EEPROM_Busy": 12,
  13. "MOD1": 11,
  14. "MOD0": 10,
  15. "CONV2": 9,
  16. "CONV1": 8,
  17. "CONV0": 7,
  18. "AVG1": 6,
  19. "AVG0": 5,
  20. "T/nA": 4,
  21. "POL": 3,
  22. "DR/Alert": 2,
  23. "Soft_Reset": 1,
  24. "--": 0
  25. }
  26. DEFAULT_CONFIG_INT = 554
  27. def __init__(self, name: str, i2c: machine.I2C|machine.SoftI2C, i2c_addr, config_int):
  28. self.name = name
  29. self.i2c_addr = i2c_addr
  30. self.i2c = i2c
  31. self.NIST_ID = int.from_bytes(self.i2c.readfrom_mem(self.i2c_addr, self.NIST_ADDR, 2), "big")
  32. # Set configuration
  33. self.write_configuration_integer(config_int)
  34. def bytes_to_temperature(self, binary:bytes):
  35. """Converts a 2's complement 16 bit value to the appropriate temperature value."""
  36. val = int.from_bytes(binary, "big")
  37. if (val & (1 << (self.TEMP_SIZE - 1))) != 0:
  38. val = val - (1 << self.TEMP_SIZE)
  39. return val * TMP117.RESOLUTION
  40. def int_to_config_dict(self, integer:int):
  41. """Converts a configuration """
  42. assert integer < 2**(16)
  43. bits = list(f"{integer:016b}")
  44. bits.reverse()
  45. result = {}
  46. for key in self.CONFIG_REGISTER_MAP.keys():
  47. result[key] = bits[self.CONFIG_REGISTER_MAP[key]]
  48. return result
  49. def config_dict_to_int(self, config_dict):
  50. array = [None for _ in range(16)]
  51. for option in config_dict.keys():
  52. array[self.CONFIG_REGISTER_MAP[option]] = config_dict[option]
  53. array.reverse()
  54. bit_string = ""
  55. for bit in array:
  56. bit_string += str(bit)
  57. write_byte = int(bit_string, 2)
  58. def write_configuration_integer(self, config_int:int):
  59. write_byte = config_int.to_bytes(2, "big")
  60. self.i2c.writeto_mem(self.i2c_addr, self.CONFIG_ADDR, write_byte)
  61. def read_configuration_integer(self):
  62. binary = self.i2c.readfrom_mem(self.i2c_addr, self.CONFIG_ADDR, 2)
  63. integer = int.from_bytes(binary, "big")
  64. return integer
  65. def read_temperature(self):
  66. binary = self.i2c.readfrom_mem(self.i2c_addr, self.TEMP_ADDR, 2)
  67. return self.bytes_to_temperature(binary)