control.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env python3
  2. import struct
  3. from pyftdi.spi import SpiController
  4. class BoardControlBase(object):
  5. def __init__(self, addr='ftdi://ftdi:2232h/1', spi_frequency=30e6, spi_cs=None):
  6. # SPI link
  7. self.spi_frequency = spi_frequency
  8. self.spi = SpiController(cs_count=3)
  9. self.spi.configure(addr)
  10. if spi_cs is not None:
  11. self.slave = self.spi.get_port(cs=spi_cs, freq=self.spi_frequency, mode=0)
  12. else:
  13. self.slave = self._spi_probe()
  14. def _spi_probe(self):
  15. for cs in [0, 2]:
  16. port = self.spi.get_port(cs=cs, freq=self.spi_frequency, mode=0)
  17. r = port.exchange(b'\x00', duplex=True)[0]
  18. if r != 0xff:
  19. return port
  20. raise RuntimeError('Automatic SPI CS probe failed')
  21. def reg_w16(self, reg, v):
  22. self.slave.exchange(struct.pack('>BH', reg, v))
  23. def reg_w8(self, reg, v):
  24. self.slave.exchange(struct.pack('>BB', reg, v))
  25. def reg_burst(self, reg, data):
  26. self.slave.exchange(bytearray([reg]) + data)
  27. def read_status(self):
  28. rv = self.slave.exchange(bytearray(2), duplex=True)
  29. return rv[0] | rv[1]
  30. def arg_group_setup(group):
  31. group.add_argument('--spi-freq', type=float, help='SPI frequency in MHz', default=30.0)
  32. group.add_argument('--spi-cs', type=int, help='SPI slave select id (-1 = probe)', default=-1)
  33. group.add_argument('--ftdi-addr', type=str, help='FTDI address', default='ftdi://ftdi:2232h/1')
  34. def arg_to_kwargs(args):
  35. return {
  36. 'spi_frequency': args.spi_freq * 1e6,
  37. 'spi_cs': args.spi_cs if (args.spi_cs >= 0) else None,
  38. 'addr': args.ftdi_addr,
  39. }