Advertisement
DeaD_EyE

mcp3208 micropython

Sep 13th, 2022 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. from time import sleep_ms
  2.  
  3. class ChipSelect:
  4.     def __init__(self, pin):
  5.         pin.value(1)
  6.         self._pin = pin
  7.  
  8.     def __enter__(self):
  9.         self._pin.value(0)
  10.  
  11.     def __exit__(self, exc_type, exc_obj, exc_tb):
  12.         self._pin.value(1)
  13.  
  14.  
  15. class MCP3208:
  16.     WIDTH = 2**12
  17.  
  18.     def __init__(self, spi, cs, ref_voltage=3.3):
  19.         """
  20.        Create MCP3208 instance
  21.  
  22.        Args:
  23.            spi: configured SPI bus
  24.            cs:  pin to use for chip select
  25.            ref_voltage: reference voltage
  26.        """
  27.         self.cs = ChipSelect(cs)
  28.         self._spi = spi
  29.         self._buffer_in = bytearray(3)
  30.         self._buffer_out = bytearray(3)
  31.         self._ref_voltage = ref_voltage
  32.  
  33.     @property
  34.     def reference_voltage(self) -> float:
  35.         """Returns the MCP3xxx's reference voltage as a float."""
  36.         return self._ref_voltage
  37.  
  38.     def read_raw(self, channel, is_differential=False):
  39.         """
  40.        read a voltage or voltage difference using the MCP3208.
  41.  
  42.        Args:
  43.            pin: the pin to use
  44.            is_differential: if true, return the potential difference between two pins,
  45.  
  46.  
  47.        Returns:
  48.            voltage in range [0, 4095] where 4095 = VREF (3V3)
  49.  
  50.        """
  51.         # self._out_buf[0] = 1 << 7 | (not is_differential) << 6 | channel << 3
  52.         self._buffer_out = bytearray(
  53.             [
  54.                 1 << 2 | (not is_differential) << 1 | (channel & 0x04) >> 2,
  55.                 (channel & 0x03) << 6,
  56.                 0,
  57.             ]
  58.         )
  59.         # print(self._buffer_out)
  60.         with self.cs:
  61.             self._spi.write_readinto(self._buffer_out, self._buffer_in)
  62.             # self._spi.write(self._buffer_out)
  63.             # self._spi.readinto(self._buffer_in)
  64.            
  65.         return (self._buffer_in[1] & 0x0F) << 8 | self._buffer_in[2]
  66.  
  67.     def read(self, channel, is_differential=False):
  68.         return (
  69.             self.read_raw(channel, is_differential)
  70.             / (self.WIDTH - 1)
  71.             * self.reference_voltage
  72.         )
  73.  
  74.  
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement