mcp3428.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # I2C address of the device
  2. MCP3428_DEFAULT_ADDRESS = 0x68
  3. # MCP3428 Configuration Command Set
  4. MCP3428_CMD_NEW_CNVRSN = 0x80 # Initiate a new conversion(One-Shot Conversion mode only)
  5. CHANNEL = {
  6. 1: 0x00, # Channel-1 Selected
  7. 2: 0x20, # Channel-2 Selected
  8. 3: 0x40, # Channel-3 Selected
  9. 4: 0x60 # Channel-4 Selected
  10. }
  11. MCP3428_CMD_MODE_CONT = 0x10 # Continuous Conversion Mode
  12. MCP3428_CMD_MODE_ONESHOT = 0x00 # One-Shot Conversion Mode
  13. RESOLUTION = {
  14. 12: 0x00, # 240 SPS (12-bit)
  15. 14: 0x04, # 60 SPS (14-bit)
  16. 16: 0x08 # 15 SPS (16-bit)
  17. }
  18. GAIN = {
  19. 1: 0x00, # PGA Gain = 1V/V
  20. 2: 0x01, # PGA Gain = 2V/V
  21. 4: 0x02, # PGA Gain = 4V/V
  22. 8: 0x03 # PGA Gain = 8V/V
  23. }
  24. MCP3428_CMD_READ_CNVRSN = 0x00 # Read Conversion Result Data
  25. import smbus2 as smbus
  26. from ..api.i2c_handler import I2CDevice
  27. class MCP3428(I2CDevice):
  28. default_address = MCP3428_DEFAULT_ADDRESS
  29. def initialize(self, address: int):
  30. self.bus = smbus.SMBus(1)
  31. self.address = address
  32. def config_channel(self, channel: int, gain=1, resolution=12):
  33. """Select the Configuration Command from the given provided values"""
  34. self.gain = gain
  35. self.resolution = resolution
  36. CONFIG_CMD = (MCP3428_CMD_MODE_CONT | RESOLUTION[resolution] | GAIN[gain] | CHANNEL[channel])
  37. self.bus.write_byte(self.address, CONFIG_CMD)
  38. def read_value(self) -> float:
  39. raw_adc = self._read_adc()
  40. res_per_bit = 2.048/2**(self.resolution-1)
  41. return raw_adc*res_per_bit/self.gain
  42. def _read_adc(self):
  43. """Read data back from MCP3428_CMD_READ_CNVRSN(0x00), 2 bytes
  44. raw_adc MSB, raw_adc LSB"""
  45. read = smbus.i2c_msg.read(self.address, 2)
  46. self.bus.i2c_rdwr(read)
  47. data = list(read)
  48. # Convert the data to 12-bits
  49. raw_adc = ((data[0] & 0x0F) * 256) + data[1]
  50. if raw_adc > 2047:
  51. raw_adc -= 4095
  52. return raw_adc