def begin(self): try: self.ctrl = SpiController(cs_count=1) s = 'ftdi://0x0403:0x6011/1' self.ctrl.configure(s) self.slave = self.ctrl.get_port(cs=0, freq=6E6, mode=3) self.slave.set_frequency(8000000) self.gpio = self.ctrl.get_gpio() self.gpio.set_direction( 0x10, 0x10) # direction for the fet controller is OUTPUT (1) self.gpio.write(0x10) time.sleep(0.1) # to account for using separate ports for power and comms: self.backup_ctrl = SpiController(cs_count=1) self.backup_gpio = None if not s == 'ftdi://0x0403:0x6011/1': backup_s = 'ftdi://0x0403:0x6011/1' self.backup_ctrl.configure(backup_s) self.backup_gpio = self.backup_ctrl.get_gpio() self.backup_gpio.set_direction(0x10, 0x10) self.backup_gpio.write(0x10) time.sleep(1) except Exception as err: print('Error in initialising the FTDI driver ...:', err)
def test_spi_controller(self): """Demo instanciation with an SpiController. """ spi = SpiController(cs_count=1) spi.configure(self.ftdi_url) flash = SerialFlashManager.get_from_controller(spi, cs=0, freq=self.frequency)
def initialize(): global spi global gpio # Configure controller with one CS ctrl = SpiController(cs_count=1, turbo=True) # ctrl.configure('ftdi:///?') # Use this if you're not sure which device to use # Windows users: make sure you've loaded libusb-win32 using Zadig try: ctrl.configure(config.FTDI_URL) except: print("Can't configure FTDI. Possible reasons:") print( " 1. As a current Linux user you don't have an access to the device.\n" " Solution: https://eblot.github.io/pyftdi/installation.html\n" " 2. You use the wrong FTDI URL. Replace FTDI_URL in config.py with one of the following:\n" ) ctrl.configure('ftdi:///?') sys.exit(1) # Get SPI slave # CS0, 10MHz, Mode 0 (CLK is low by default, latch on the rising edge) spi = ctrl.get_port(cs=0, freq=10E6, mode=0) # Get GPIO gpio = ctrl.get_gpio() gpio.set_direction(0x10, 0x10)
def __init__(self): # Instanciate a SPI controller spi = SpiController() spi.configure('ftdi://ftdi:232h:FT0KGOUA/1') # The sensor AMT203-V is the slave # https://www.cui.com/product/resource/amt20.pdf self.slave = spi.get_port(cs=0, freq=spi.frequency / 32, mode=0)
def __init__(self): self._spi = SpiController(cs_count=1, cs_pol=0) self._freq = 1E6 self._mode = 0 self._bidir = True # Maximum number of read cycles to wait while looking for the # Ready status after each write self._write_timeout_cnt = 25 # According to the datasheet, the maximum write time is 6 ms self._Twc = 0.006 # The opcodes are a full byte to make it easy to use with the # byte interface of SpiController. These opcodes also include # the start bit (SB), which is simply the left-most '1' # bit. The actual 2-bit opcode (OC) follows this start bit. # # The instructions ERAL, EWDS, EWEN and WRAL require a special # address byte to complete the opcode. So they are 2 element # lists whereas the others are single element lists. self._SBOC_erase = [0x07] self._SBOC_eral = [0x04, 0x80] # requires EEPROM Vcc >= 4.5V self._SBOC_ewds = [0x04, 0x00] self._SBOC_ewen = [0x04, 0xc0] self._SBOC_read = [0x06] self._SBOC_write = [0x05] self._SBOC_wral = [0x04, 0x40] # requires EEPROM Vcc >= 4.5V
def __init__(self, readback=True, ftdi_url='ftdi://ftdi:232h/1'): """An FT232H chip must be connected to your computer for this constructor to succeed. It sets up the SPI/GPIO interface and configures readback. When readback is enabled, set_tap will throw an error if the readback of any write does not match what was programmed. Readback does have an impact on performance because it requires an extra SPI transaction for every call to set_tap, but for safety it should not be disabled unless speed is your top priority. Note that for readback to work, the appropriate switch on the board must be set. Args: readback (bool, optional): Set to False to disable readback error checking """ self._readback = readback # Setup SPI interface self._spi_controller = SpiController() self._spi_controller.configure(ftdi_url) self._spi = self._spi_controller.get_port(cs=0, mode=0, freq=1e6) # Setup GPIO interface self._gpio = self._spi_controller.get_gpio() self._gpio.set_direction(1 << self.APPLY_PIN, 1 << self.APPLY_PIN) # make APLS an output self._set_apply(False) # We're always going to use address 0. This is here just in case that changes. self._addr = 0
def __init__(self): # Instanciate a SPI controller self._spi = SpiController() # Configure the first interface (IF/1) of the FTDI device as a SPI master self._spi.configure('ftdi://ftdi:2232h/2') # Get a SPI port to a SPI slave w/ /CS on A*BUS3 and SPI mode 0 @ 12MHz self._slave = self._spi.get_port(cs=1, freq=500e3, mode=0)
def __init__(self, spi_frequency=5e6): # Params self.spi_frequency = spi_frequency # SPI link self.spi = SpiController(cs_count=3) self.spi.configure('ftdi://ftdi:2232h/1') self.slave = self.spi.get_port(cs=2, freq=self.spi_frequency, mode=0)
def test_usb_device(self): """Demo instanciation from an existing UsbDevice. """ candidate = Ftdi.get_identifiers(self.ftdi_url) usbdev = UsbTools.get_device(candidate[0]) spi = SpiController(cs_count=1) spi.configure(usbdev, interface=candidate[1]) flash = SerialFlashManager.get_from_controller(spi, cs=0, freq=self.frequency)
def __init__(self): from pyftdi.spi import SpiController self._spi = SpiController(cs_count=1) self._spi.configure('ftdi://ftdi:ft232h/1') self._port = self._spi.get_port(0) self._port.set_frequency(100000) self._port._cpol = 0 self._port._cpha = 0 # Change GPIO controller to SPI Pin.ft232h_gpio = self._spi.get_gpio()
def __init__(self, device='ftdi://ftdi:232h/1', debug=False): self.device_str = device self.debug = debug self.ctrl = SpiController(silent_clock=False) self.ctrl.configure(device, cs_count=1) self.spi = self.ctrl.get_port(cs=0, freq=100000) self.gpio = self.ctrl.get_gpio() direction = self.gpio.direction self.gpio.set_direction(0x30, 0x10) # Add reset as output self.gpio.write(0x10)
def get_flash_device(url, cs=0, freq=None): """Obtain an instance of the detected flash device""" ctrl = SpiController(silent_clock=False) ctrl.configure(url) spi = ctrl.get_port(cs, freq) jedec = SerialFlashManager.read_jedec_id(spi) if not jedec: # it is likely that the latency setting is too low if this # condition is encountered raise SerialFlashUnknownJedec("Unable to read JEDEC Id") flash = SerialFlashManager._get_flash(spi, jedec) flash.set_spi_frequency(freq) return flash
def main(argv): """ Entry point for bme280-monitor.py Arguments: argv: command line arguments """ now = datetime.utcnow().strftime("%FT%TZ") args = process_arguments(argv) # Connect to the sensor. ctrl = SpiController() ctrl.configure(args.device) spi = ctrl.get_port(Port[args.cs].value) spi.set_frequency(args.frequency) try: bme280 = Bme280spi(spi) except RuntimeError as err: print(err) sys.exit(1) if "{}" in args.path: filename = args.path.format(now) else: filename = args.path # Write datafile header. with open(filename, "a") as datafile: datafile.write("# BME280 data.\n# Started monitoring at {}.\n".format(now)) datafile.write("# Per line, the data items are:\n") datafile.write("# * UTC date and time in ISO8601 format\n") datafile.write("# * Temperature in °C\n") datafile.write("# * Pressure in Pa\n") datafile.write("# * Relative humidity in %.\n") # Read and write the data. try: # Throw the first read away; bogis pressure value. bme280.read() while True: now = datetime.utcnow().strftime("%FT%TZ") temperature, pressure, humidity = bme280.read() line = "{} {:.2f} {:.0f} {:.2f}\n".format( now, temperature, pressure, humidity ) with open(filename, "a") as datafile: datafile.write(line) time.sleep(args.interval) except KeyboardInterrupt: sys.exit(1)
def __init__(self): # pylint: disable=import-outside-toplevel from pyftdi.spi import SpiController # pylint: enable=import-outside-toplevel self._spi = SpiController(cs_count=1) self._spi.configure(get_ftdi_url()) self._port = self._spi.get_port(0) self._port.set_frequency(100000) self._port._cpol = 0 self._port._cpha = 0 # Change GPIO controller to SPI Pin.ft232h_gpio = self._spi.get_gpio()
def ftdi_spi(device='ftdi://::/1', bus_speed_hz=12000000, gpio_CS=3, gpio_DC=5, gpio_RST=6, reset_hold_time=0, reset_release_time=0): """ Bridges an `SPI <https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus>`_ (Serial Peripheral Interface) bus over an FTDI USB device to provide :py:func:`data` and :py:func:`command` methods. :param device: A URI describing the location of the FTDI device. If ``None`` is supplied (default), ``ftdi://::/1`` is used. See `pyftdi <https://pypi.org/project/pyftdi>`_ for further details of the naming scheme used. :type device: string :param bus_speed_hz: SPI bus speed, defaults to 12MHz. :type bus_speed_hz: int :param gpio_CS: The ADx pin to connect chip select (CS) to (defaults to 3). :type gpio_CS: int :param gpio_DC: The ADx pin to connect data/command select (DC) to (defaults to 5). :type gpio_DC: int :param gpio_RST: The ADx pin to connect reset (RES / RST) to (defaults to 6). :type gpio_RST: int :param reset_hold_time: The number of seconds to hold reset active. Some devices may require a duration of 100ms or more to fully reset the display (default:0) :type reset_hold_time: float :param reset_release_time: The number of seconds to delay afer reset. Some devices may require a duration of 150ms or more after reset was triggered before the device can accept the initialization sequence (default:0) :type reset_release_time: float .. versionadded:: 1.9.0 """ from pyftdi.spi import SpiController controller = SpiController(cs_count=1) controller.configure(device) slave = controller.get_port(cs=gpio_CS - 3, freq=bus_speed_hz, mode=0) gpio = controller.get_gpio() # RESET and DC configured as outputs pins = _ftdi_pin(gpio_RST) | _ftdi_pin(gpio_DC) gpio.set_direction(pins, pins & 0xFF) serial = spi( __FTDI_WRAPPER_SPI(controller, slave), __FTDI_WRAPPER_GPIO(gpio), gpio_DC=gpio_DC, gpio_RST=gpio_RST, reset_hold_time=reset_hold_time, reset_release_time=reset_release_time) serial._managed = True return serial
def __init__(self, addr='ftdi://ftdi:2232h/1', spi_frequency=30e6, spi_cs=None): # SPI link self.spi_frequency = spi_frequency self.spi = SpiController(cs_count=3) self.spi.configure(addr) if spi_cs is not None: self.slave = self.spi.get_port(cs=spi_cs, freq=self.spi_frequency, mode=0) else: self.slave = self._spi_probe()
def setConfigure(ftdi_interface, ccp_header_file): spi = SpiController() spi.configure(ftdi_interface) global slave slave = spi.get_port(cs=0, freq=12E6, mode=0) global ccp_header ccp_header = cpp_header_parser.read_header(ccp_header_file) def makeup_data(keylist): return [ReadFromCppHeader(key) for key in keylist] blockWrite(ccp_header["gpo_data_15_to_0"], makeup_data(configDesignVals)) blockWrite(ccp_header["port_cfg_00"], makeup_data(portConfigDesignVals)) blockWrite(ccp_header["dac_data_port_00"], makeup_data(dacDesignVals))
def main(argv): """ Entry point for bmp280-monitor.py Arguments: argv: command line arguments """ now = datetime.utcnow().strftime('%FT%TZ') args = process_arguments(argv) # Connect to the sensor. ctrl = SpiController() ctrl.configure(args.device) spi = ctrl.get_port(Port[args.cs].value) spi.set_frequency(args.frequency) try: bmp280 = Bmp280spi(spi) except RuntimeError as err: print(err) sys.exit(1) if '{}' in args.path: filename = args.path.format(now) else: filename = args.path # Write datafile header. with open(filename, 'a') as datafile: datafile.write( '# BMP280 data.\n# Started monitoring at {}.\n'.format(now)) datafile.write('# Per line, the data items are:\n') datafile.write('# * UTC date and time in ISO8601 format\n') datafile.write('# * Temperature in °C\n') datafile.write('# * Pressure in Pa\n') # Read and write the data. try: while True: now = datetime.utcnow().strftime('%FT%TZ') temperature, pressure = bmp280.read() line = '{} {:.2f} {:.0f}\n'.format(now, temperature, pressure) with open(filename, 'a') as datafile: datafile.write(line) time.sleep(args.interval) except KeyboardInterrupt: sys.exit(1)
def ftdi_spi(device='ftdi://::/1', bus_speed_hz=12000000, gpio_CS=3, gpio_DC=5, gpio_RST=6): """ Bridges an `SPI <https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus>`_ (Serial Peripheral Interface) bus over an FTDI USB device to provide :py:func:`data` and :py:func:`command` methods. :param device: A URI describing the location of the FTDI device. If ``None`` is supplied (default), ``ftdi://::/1`` is used. See `pyftdi <https://pypi.python.org/pypi/pyftdi>`_ for further details of the naming scheme used. :type device: string :param bus_speed_hz: SPI bus speed, defaults to 12MHz. :type bus_speed_hz: int :param gpio_CS: The ADx pin to connect chip select (CS) to (defaults to 3). :type gpio_CS: int :param gpio_DC: The ADx pin to connect data/command select (DC) to (defaults to 5). :type gpio_DC: int :param gpio_RST: The ADx pin to connect reset (RES / RST) to (defaults to 6). :type gpio_RST: int .. versionadded:: 1.9.0 """ from pyftdi.spi import SpiController controller = SpiController(cs_count=1) controller.configure(device) slave = controller.get_port(cs=gpio_CS - 3, freq=bus_speed_hz, mode=0) gpio = controller.get_gpio() # RESET and DC configured as outputs pins = _ftdi_pin(gpio_RST) | _ftdi_pin(gpio_DC) gpio.set_direction(pins, pins & 0xFF) serial = spi(__FTDI_WRAPPER_SPI(controller, slave), __FTDI_WRAPPER_GPIO(gpio), gpio_DC=gpio_DC, gpio_RST=gpio_RST) serial._managed = True return serial
def __init__(self, ftdi_url, spi_freq=1E6): """Configure the FTDI interface. Keyword arguments: ftdi_url -- device url, which can be obtained by Ftdi.show_devices() freq -- SPI frequency up to 8E6 (for FPGA running on 64 MHz) """ # Configure SPI master self._spi_ctrl = SpiController() self._spi_ctrl.configure(ftdi_url + '2') # second port - channel B self._spi_port = self._spi_ctrl.get_port(cs=0, freq=spi_freq, mode=0) # Configure FPGA logic reset (ICE_RESET_FT) self._spi_gpio = self._spi_ctrl.get_gpio() self._spi_gpio.set_direction(1 << self.GPIO_RESET_LOGIC_POS, 1 << self.GPIO_RESET_LOGIC_POS) self._spi_gpio.write(0) # Configure FPGA configuration reset (ICE_RESET) self._gpio_ctrl = GpioAsyncController() self._gpio_ctrl.configure(ftdi_url + '1', # first port - channel A direction=(1 << self.GPIO_RESET_CONFIG_POS), frequency=1e6, initial=(1 << self.GPIO_RESET_CONFIG_POS)) self._gpio_ctrl.write(1 << self.GPIO_RESET_CONFIG_POS)
import sys import time from os import environ from binascii import hexlify from typing import Iterable, Optional, Tuple, Union import numpy as np from pyftdi.misc import pretty_size from pyftdi.spi import SpiController, SpiPort # ftdi://ftdi:232h:2:11/1 (UPduino v3.0) ftdi_url = environ.get('FTDI_DEVICE', 'ftdi://::/1') print('Using FTDI device %s' % ftdi_url) ctrl = SpiController(cs_count=2) ctrl.configure(ftdi_url) spi_freq = 1e6 spi1 = ctrl.get_port(cs=1, freq=spi_freq, mode=0) spi0 = ctrl.get_port(cs=0, freq=spi_freq, mode=0) #gpio = ctrl.get_gpio() #gpio.set_direction(0x80, 0x80) # Reset the FPGA and get the Flash ID #gpio.write(0x00) #time.sleep(0.1) #spi1.exchange([0xAB], 1) # Wake up the flash #jedec_id = spi1.exchange([0x9f,], 3) #print(jedec_id) #spi1.exchange([0xB9], 1) # Put the flash to sleep # Release from reset #gpio.write(0x80) #gpio.set_direction(0x0, 0x0)
import time import sys from pyftdi.spi import SpiController import FTDISPI import JSONFile spi = SpiController() spi.configure('ftdi:///2') slave = spi.get_port( \ cs=0, \ freq=1e6, \ mode=0 \ ) dac = FTDISPI.Interface( \ FTDISPI.MPSSE(slave), \ defaultMap = "DAC38RF8x.json", \ currentState = "DAC_current_state.json", \ previousState = "DAC_previous_state.json", ) def VCO_OK(Tj, LFVOLT): if (Tj >= 108 and (LFVOLT == 5 or LFVOLT == 6)): return True elif (Tj >= 92 and (LFVOLT == 4 or LFVOLT == 5)):
def is_busy(device): return get_status(device) & SR_WIP if len(sys.argv) < 2: print("Usage: raptor_flash.py <file>") sys.exit() file_path = sys.argv[1] if not os.path.isfile(file_path): print("File not found.") sys.exit() spi = SpiController(cs_count=1, turbo=True) # spi.configure(vendor=0x0403, product=0x6014, interface=1) spi.configure('ftdi://::/1') slave = spi.get_port(cs=0, freq=12E6, mode=0) # Chip select is 0 -- corresponds to D3 slave.write([CMD_RESET_CHIP]) jedec = slave.exchange([CMD_JEDEC_DATA], 3) print("JEDEC = {}".format(binascii.hexlify(jedec))) if jedec[0:1] != bytes.fromhex('ef'): print("Winbond SRAM not found") sys.exit() report_status(jedec)
def __init__(self): self._spi = SpiController(cs_count=3)
def setUp(self): self._spi = SpiController(cs_count=1) url = environ.get('FTDI_DEVICE', 'ftdi://ftdi:2232h/1') self._spi.configure(url) self._port = self._spi.get_port(0, freq=1E6, mode=0) self._io = self._spi.get_gpio()
def __init__(self, debug=False): self._debug = debug self._spi = SpiController(cs_count=2) self._spi_port = None self._io_port = None self._io = 0
def main(): done_stdin = False parser = argparse.ArgumentParser( prog="spitest", formatter_class=argparse.RawDescriptionHelpFormatter, usage=USAGE, description=__doc__) parser.add_argument('--version', action='store_true', help='Show version and exit') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output during processing') parser.add_argument( '-f', '--flippy', action='store_true', help='Flip the SPI/JTAG control GPIO 10 times and exit') parser.add_argument( '-l', '--length', type=int, action='store', help='Construct and send a message of specified length') parser.add_argument('-j', '--jtag', action='store_true', help='Set SPI/JTAG control to JTAG and exit') parser.add_argument('message', nargs='*', metavar='input', default='1234', help='message to send in 4 byte chunks') args = parser.parse_args() if args.version: show_and_exit(__file__, ["pyftdi"]) if (args.verbose): log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(message)s") # Instanciate a SPI controller spi = SpiController(cs_count=1) # interfaces start from 1 here, so this is Channel A (called 0 in jtag) spi.configure('ftdi://ftdi:2232h/1') # Get a port to a SPI slave w/ /CS on A*BUS3 and SPI mode 0 @ 1MHz slave = spi.get_port(cs=0, freq=1E6, mode=0) # Get GPIO port to manage extra pins # BUS4 = JTAG TRST_N, BUS5 = JTAG SRST_N, BUS6 = JTAG_SPIN # Note: something makes FTDI default to BUS6 low, selected that for SPI # otherwise SRST being default low holds the chip in reset # pyftdi Set Direction also forces the output to zero # so initially make SRST an input w/pullup in FPGA in case SPI/JTAG was # initially JTAG gpio = spi.get_gpio() gpio.set_direction(0x40, 0x40) time.sleep(1) gpio.set_direction(0x70, 0x70) if args.jtag: gpio.write(0x70) return gpio.write(0x30) if args.flippy: for i in range(10): print("Select SPI") gpio.write(0x30) time.sleep(2) print("Select JTAG") gpio.write(0x70) time.sleep(2) return print("Select SPI") gpio.write(0x30) # Synchronous exchange with the remote SPI slave if args.length: s = '' for i in range(args.length): s += hex(i & 15)[-1] else: s = '' for m in args.message: s += m + ' ' s = s[:-1] # remove extra space put on end # pad to ensure multiple of 4 bytes filled = len(s) % 4 if filled: s += '....'[filled:] while len(s): write_buf = bytes(s[:4], encoding='utf8') read_buf = slave.exchange(write_buf, duplex=True).tobytes() print("Got " + str(read_buf)) s = s[4:]
def __init__(self): self._spi = SpiController()
def setUp(self): self._spi = SpiController(cs_count=1) self._spi.configure(self.url, debug=self.debug) self._port = self._spi.get_port(0, freq=1E6, mode=0)
def __init__(self): # change GPIO controller to SPI from pyftdi.spi import SpiController self._spi = SpiController(cs_count=1) self._spi.configure('ftdi:///1') Pin.ft232h_gpio = self._spi.get_gpio()