예제 #1
0
def read_adc(spi: busio.SPI, channel: int) -> int:
    """ Read a single ADC channel of the MCP3008  """
    # TODO: This is still kinda slow, investigate Python's 'spidev'
    # library or https://iosoft.blog/2020/06/11/fast-data-capture-raspberry-pi/
    rx_buf = bytearray(3)
    tx_buf = bytearray((0x01, 0x80 | (channel << 4), 0x00))
    with open(f'/sys/class/gpio/gpio{CS_PIN}/value', 'w') as cs_file:
        cs_file.write('0')
    spi.write_readinto(tx_buf, rx_buf)
    with open(f'/sys/class/gpio/gpio{CS_PIN}/value', 'w') as cs_file:
        cs_file.write('1')
    raw_val = ((rx_buf[1] & 0x3) << 8) | rx_buf[2]
    return raw_val
예제 #2
0
class SPIBus(object):
    """SPI bus access."""
    def __init__(self, freq, sc, mo, mi):
        self._spi = SPI(sc, mo, mi)
        if not self._spi.try_lock():
            print("ERROR: busio.SPIBus: no lock for configure()")
        else:
            try:
                self._spi.configure(baudrate=freq)
            finally:
                self._spi.unlock()

    @property
    def bus(self):
        return self._spi

    def write_readinto(self, wbuf, rbuf):
        if self._spi.try_lock():
            try:
                self._spi.write_readinto(wbuf, rbuf)
            finally:
                self._spi.unlock()