Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Source: https://github.com/MomsFriendlyRobotCompany/mcp3208
- I removed the Adafruit dependency and added a context manager.
- Don't forget to activate SPI on your Raspberry Pi
- """
- from spidev import SpiDev
- class MCP3208:
- def __init__(self, bus=0, device=0, vref=3.3):
- """
- bus := The spi bus where MCP3208 is attached to
- device := Device selection
- vref := reference voltage
- """
- self.spi = SpiDev(bus, device)
- self.spi.max_speed_hz = 1000000
- self.vref = vref
- def __del__(self):
- self.spi.close()
- def __enter__(self):
- return self
- def __exit__(self, exc_type, exc_obj, exc_tb):
- self.spi.close()
- def read(self, channel):
- if not 0 <= channel <= 7:
- raise Exception(f"MCP3208 channel must be 0-7: {channel}")
- cmd = 128 # 1000 0000
- cmd += 64 # 1100 0000
- cmd += (channel & 0x07) << 3
- ret = self.spi.xfer2([cmd, 0x0, 0x0])
- # get the 12b out of the return
- val = (ret[0] & 0x01) << 11 # only B11 is here
- val |= ret[1] << 3 # B10:B3
- val |= ret[2] >> 5 # MSB has B2:B0 ... need to move down to LSB
- return (val & 0x0FFF) / 4096 * self.vref # ensure we are only sending 12b
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement