Advertisement
DeaD_EyE

MCP3208

Feb 5th, 2021
1,023
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. """
  2. Source: https://github.com/MomsFriendlyRobotCompany/mcp3208
  3.  
  4. I removed the Adafruit dependency and added a context manager.
  5. Don't forget to activate SPI on your Raspberry Pi
  6. """
  7.  
  8. from spidev import SpiDev
  9.  
  10.  
  11. class MCP3208:
  12.     def __init__(self, bus=0, device=0, vref=3.3):
  13.         """
  14.        bus := The spi bus where MCP3208 is attached to
  15.        device := Device selection
  16.        vref := reference voltage
  17.        """
  18.         self.spi = SpiDev(bus, device)
  19.         self.spi.max_speed_hz = 1000000
  20.         self.vref = vref
  21.  
  22.     def __del__(self):
  23.         self.spi.close()
  24.  
  25.     def __enter__(self):
  26.         return self
  27.  
  28.     def __exit__(self, exc_type, exc_obj, exc_tb):
  29.         self.spi.close()
  30.  
  31.     def read(self, channel):
  32.         if not 0 <= channel <= 7:
  33.             raise Exception(f"MCP3208 channel must be 0-7: {channel}")
  34.  
  35.         cmd = 128  # 1000 0000
  36.         cmd += 64  # 1100 0000
  37.         cmd += (channel & 0x07) << 3
  38.         ret = self.spi.xfer2([cmd, 0x0, 0x0])
  39.  
  40.         # get the 12b out of the return
  41.         val = (ret[0] & 0x01) << 11  # only B11 is here
  42.         val |= ret[1] << 3  # B10:B3
  43.         val |= ret[2] >> 5  # MSB has B2:B0 ... need to move down to LSB
  44.  
  45.         return (val & 0x0FFF) / 4096 * self.vref  # ensure we are only sending 12b
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement