def query(slave_name, command, args=[]):
  """Selects the given SPI slave, sends it the SPI command and returns the received response as a
  stripped string.
  @param slave_name: _KNOWN_SPI_SLAVES key.
  @param command: _KNOWN_SPI_SLAVES[slave_name]['commands'] key.
  @param args: list of strings to be sent as command arguments.
  """
  _select_spi_slave(slave_name)

  spi = SPI(_SPI_BUS_SETTINGS['dev'], _SPI_BUS_SETTINGS['mode'], _SPI_BUS_SETTINGS['freq_hz'])

  full_command = _KNOWN_SPI_SLAVES[slave_name]['commands'][command]
  if args:
    full_command += ' ' + ','.join(args)
    full_command += '*' + int_to_hex_string(_crc(full_command))
  full_command = (bytes(full_command, 'ascii') + _SPI_MESSAGE_SEPARATOR).ljust(_SPI_COMMAND_LENGTH,
                                                                               b'\x00')

  response = spi.transfer(full_command)
  response = response.split(_SPI_MESSAGE_SEPARATOR)[0]

  spi.close()

  printable_response = ''.join(map(lambda ascii_num: chr(ascii_num),
                                   filter(lambda char: char >= 0x20 and char < 0x7f, response)))
  return printable_response
class MCP3208(object):
    MAX_CLOCK_SPEED = 2E+6
    RESOLUTION = 0b1 << 12
    SECOND_WORD_MASK = 0b00001111

    def __init__(self):
        self.spi = SPI(
            config.get('MCP3208', 'device_file'),
            0,
            MCP3208.MAX_CLOCK_SPEED
        )
        self.Vref = config.getfloat('MCP3208', 'vref')

    def read(self):
        mosi_data = self._make_mosi_data()
        miso_data = self.spi.transfer(mosi_data)
        _, second_word, third_word = miso_data
        value = ((MCP3208.SECOND_WORD_MASK & second_word) << 8) + third_word
        return value * self.Vref / MCP3208.RESOLUTION

    def clean_up(self):
        self.spi.close()

    def _make_mosi_data(self):
        ch = config.getint('MCP3208', 'ch')
        raw_data = 0b0000011000 + ch
        first_word = (0b11100 & raw_data) >> 2
        second_word = (0b11 & raw_data) << 6
        return [first_word, second_word, 0b0]
Exemple #3
0
#analyze
from periphery import SPI

spi = SPI("/dev/spidev0.0", 1, 500 * 1000)

buff = [0x03, 0x0E, 0xFF]

txt = input("address in hex(default 0x0E):")
if txt != "":
    buff[1] = int(txt, 16)

result = spi.transfer(buff)
print("register address:0x%02X -- value:0x%02X" % (buff[1], result[2]))

spi.close()

#device tree SPI without CS
from periphery import SPI
from periphery import GPIO

CS = GPIO("/dev/gpiochip0", 12, "out")
spi = SPI("/dev/spidev0.0", 1, 1000000)

tx = [0x02, 0x0F, 0x80]
rx = [0x03, 0x0E]

CS.write(False)
spi.transfer(tx)
CS.write(True)
CS.write(False)
Exemple #4
0
#!/usr/bin/python3
from periphery import SPI
import time

spi = SPI("/dev/spidev0.0", 0, 10000)
while 1:
   data=spi.transfer([0])
   print(data)
   time.sleep(0.1)
spi.close()