i2c_handler.py 824 B

12345678910111213141516171819202122232425262728
  1. import smbus2 as smbus
  2. from ..vendor.mcp3428 import MCP3428, MCP3428_DEFAULT_ADDRESS
  3. from time import sleep
  4. class I2C:
  5. def __init__(self, channels, gain = 1, resolution = 12):
  6. self.channels = channels if isinstance(channels, list) else [channels]
  7. self.gain = gain
  8. self.resolution = resolution
  9. self.mcp = None
  10. def initialize(self):
  11. bus = smbus.SMBus(1)
  12. self.mcp = MCP3428(bus, MCP3428_DEFAULT_ADDRESS)
  13. def read_channel(self, channel):
  14. if self.mcp is None:
  15. raise RuntimeError("I2C not initialized")
  16. self.mcp.config_command(channel, self.gain, self.resolution)
  17. sleep(0.01)
  18. return self.mcp.read_adc()
  19. def read(self):
  20. return {channel: self.read_channel(channel) for channel in self.channels}