Skip to content

Instantly share code, notes, and snippets.

@SealtielFreak
Last active November 24, 2024 17:57
Show Gist options
  • Save SealtielFreak/f69e2c3cb3b1943c2a54f5cf4084f7c8 to your computer and use it in GitHub Desktop.
Save SealtielFreak/f69e2c3cb3b1943c2a54f5cf4084f7c8 to your computer and use it in GitHub Desktop.
Implementation of the interface to use the MCP3xxx family in Micropython
class MCP:
def reference_voltage(self) -> float:
"""Returns the MCP3xxx's reference voltage as a float."""
raise NotImplementedError
def read(self, pin: int | None = None, is_differential=False) -> int:
"""
read a voltage or voltage difference using the MCP3102.
Args:
pin: the pin to use
is_differential: if true, return the potential difference between two pins,
Returns:
voltage in range VREF
"""
raise NotImplementedError
class MCPSerialInterface(MCP):
def __init__(self, spi, cs, ref_voltage=3.3):
"""
Create MCP SPI instance
Args:
spi: configured SPI bus
cs: pin to use for chip select
ref_voltage: r
"""
self.cs = cs
self.cs.value(1)
self._spi = spi
self._out_buf = bytearray(3)
self._out_buf[0] = 0x01
self._in_buf = bytearray(3)
self._ref_voltage = ref_voltage
def reference_voltage(self) -> float:
return self._ref_voltage
@property
def buffers(self):
return self._out_buf, self._in_buf
class MCP3202(MCPSerialInterface):
def read(self, pin=None, is_differential=False):
self.cs.value(0)
self._out_buf[1] = ((not is_differential) << 7) | (pin << 4)
self._spi.write_readinto(self._out_buf, self._in_buf)
self.cs.value(1)
return ((self._in_buf[1] & 0x0F) << 8) + self._in_buf[2]
class MCP3301(MCPSerialInterface):
def read(self, pin=None, is_differential=False):
self.cs.value(0)
self._out_buf[1] = 0x00
self._spi.write_readinto(self._out_buf, self._in_buf)
self.cs.value(1)
signal = ((self._in_buf[0] << 8) | self._in_buf[1]) & 0x1FFF
if signal & 0x1000:
signal -= 0x2000
return signal
import time
from machine import SPI, Pin
from mcp import MCP3102
if __name__ == '__main__':
spi = SPI(1, sck=Pin(10), mosi=Pin(11), miso=Pin(12), baudrate=400000) # for Raspberry Pi Pico
cs = Pin(13, mode=Pin.OUT, value=1)
mcp = MCP3102(spi, cs)
if __name__ == "__main__":
while True:
print("Value: ", mcp.read(0))
time.sleep(0.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment