def ftdi_open(board_id, channel): """opens FTDI device function depending of the current OS""" if OS == 'Linux': return pylibftdi.Device(device_index=board_id, interface_select=channel + 1) elif OS == 'Windows': dev_list = ftdi.listDevices() if channel: i2c_channel = next(ind for ind, dev in enumerate(dev_list) if chr(dev[-1]) == 'B') return ftdi.open(i2c_channel) else: gpio_channel = next(ind for ind, dev in enumerate(dev_list) if chr(dev[-1]) == 'A') return ftdi.open(gpio_channel)
def main(): """ Send/receive data from the Papilio FPGA using the high speed mode of the FT232H. """ # Create the device list. num_devices = ft.createDeviceInfoList() if (num_devices == 0): print "No devices found." sys.exit(); print "Found {0} devices.".format(num_devices) # Get the device information for the device with sync FIFO mode. device_info = None device_index = 0 for index in range(0, num_devices): device_info = ft.getDeviceInfoDetail(devnum = index, update = False) if (device_info['description'] == 'UM232H_245FIFO'): device_index = index break if (device_info == None): print "Device not found." sys.exit() # Open the device and configure for sync FIFO mode. ft.setVIDPID(0x0403, 0x6014) device = ft.open(dev = device_index) device.setBitMode(0xFF, 0x00) # Reset mode sleep(.01) device.setBitMode(0xFF, 0x40) # Sync FIFO mode device.setLatencyTimer(2) # Receive buffer timeout in msec device.setUSBParameters(4096, 4096) # Set transfer in/out size to 4096 device.setFlowControl(FLOW_RTS_CTS, 0, 0) # Flow control method
def __init__(self, newinstance=1, ftID=None, verbose=1, vv=0): if vv: verbose = 1 if ftID == None: print("") print( "\t\t\t- ft232h : Listing connected ftd2xx device (by Serial#):" ) print("\t\t\t\t", ftd2xx.listDevices(ft.OPEN_BY_SERIAL_NUMBER)) print( "\t\t\t- ft232h : Listing connected ftd2xx device (by description):" ) print("\t\t\t\t", ftd2xx.listDevices(ft.OPEN_BY_DESCRIPTION)) self.ftID = int( input( "\n>> Choose your device and input the list index (0 ~ ): " )) else: self.ftID = ftID if verbose: print("\t\t\t- ft232h : Opening device by given ftID:", self.ftID) self.dev = ftd2xx.open(self.ftID) if newinstance: self._bringup_configmode(verbose, vv) self._bringup_syncmpsse(verbose, vv) self._bringup_configmpsse(verbose, vv) return
def connect_ftdi(self): import ftd2xx import ftd2xx.defines as fd devices = ftd2xx.listDevices() if not self.serial_number in devices: print("No device found. Exiting...") return None else: ii = devices.index(self.serial_number) print("Initializing device...") device = ftd2xx.open(ii) device.setBaudRate(self.baud_rate) # time.sleep(50/1000) time.sleep(1) device.setDataCharacteristics(fd.BITS_8, fd.STOP_BITS_1, fd.PARITY_NONE) # device.setFlowControl() device.purge(fd.PURGE_RX | fd.PURGE_TX) # time.sleep(50/1000) time.sleep(1) device.resetDevice() time.sleep(1) device.setFlowControl(fd.FLOW_RTS_CTS, 0, 0) device.setRts() print(device.getDeviceInfo()) self.device = device
def init(self): # init initialise the output pins logging.info("init.") try: self.state = resetState.SET try: self.device = ftd.open(0) # Open first FTDI device except: self.device = None return di = self.device.getDeviceInfo() OP = 0x01 # Bit mask for output D0 self.device.setBitMode( OP, 1) # Set pin as output, and async bitbang mode self.device.write(str(OP)) # Set output high self.device.write(str(0)) # Set output low except: logging.info("Exception") state = resetState.INIT if self.device is not None: self.device.close() else: state = resetState.SET self.reseterTHD = threading.Thread( target=reseter_state_machine_run, args=(self, )) self.reseterTHD.start() return state
def open_ft4222_by_index(index): """ Creates and returns a new FT4222 for the FTDI device with the specified index. """ d2xx_obj = ftd2xx.open(index) return FT4222(d2xx_obj)
def __init__(self): # list devices by description, returns tuple of attached devices description strings d = ftd2xx.listDevices() print d try: self.device = ftd2xx.open(0) print self.device self.set_up_device() self.configure_command(self.device, "t11001") # configure trigger time self.configure_command(self.device, "t_020") # configure trigger timeout self.configure_command(self.device, "is_07") # i2c speed 400kHz self.configure_command( self.device, "ip_0") # control pin off (device turned off) # read version time.sleep(0.005) self.device.write("v\r\n") time.sleep(0.005) if self.device.getQueueStatus() > 0: i = self.device.read(self.device.getQueueStatus()) print "version = " + i[1:] except ftd2xx.ftd2xx.DeviceError: print "Unable to open 'EM2130 device'." self.device = ftd2xx.ftd2xx.DEVICE_NOT_FOUND
def open(idx=0): try: d = ftd.open(idx) d.resetDevice() d.purge() except: d = None return (d)
def getFTDIserialNumber(self): d = ftd.open(0) deviceList = d.getDeviceInfo() self.deviceSerialNum = deviceList['serial'] # self.deviceSerialNum = self.deviceSerialNum[:0] print("FTDI Serial Number is: " + str(self.deviceSerialNum)) d.close() return str(self.deviceSerialNum)
def _open(self, settings: Settings): self._settings_changed.clear() try: self.close() self.interface = ftd2xx.open(0) except DeviceError as e: raise FTDINoCableError('No FTDI cable connected') from e else: self.settings = settings self.next_tx = time() + self.instrument.TX_WAIT_S self.baud = BaudrateContext(self)
def openUSB(name_byte_array): for i in range(16): try: usb = ftd2xx.open(i) except: continue if usb.description==name_byte_array: print('opened usb%d: %s' % (i, usb.description,) ) return usb else: usb.close()
def __init__(self, vend_prod_id, port_name, timeout=1.0, baud_rate=9600): import ftd2xx # set up ftdi library for loading the specified device ftd2xx.setVIDPID( *vend_prod_id) # this argument is a tuple, so we unpack it tmp = ftd2xx.open( port_name) # can't assign member variables before init. Oh well tmp.setBaudRate(9600) # tmp.setTimeouts(15, 50) serial_number = tmp.eeRead().SerialNumber COM.__init__(self, serial_number, port_name, timeout, baud_rate) self._dev = tmp
def connect(self): if self.deviceIndex >= 0 : print('Connecting to device with index %d'% self.deviceIndex) self.dev = ftd2xx.open(self.deviceIndex) #FT4HNA7Z self.status = 1 time.sleep(0.1) self.dev.setBitMode(0x00, 0x40) print('Device connected') elif ftd2xx.listDevices(0): print("no FTDI devices to be connected") self.messagebox.showinfo(title=None, message="Logic Analyzer was not found")
def connect(self, id=None): """Connects to a sensor Use the optional id argument to specify a non-default sensor""" if id is None: id = 0 try: self.sensor = FT.open(id) except FT.DeviceError: print("Error: Device not found") raise self.sensor.setUSBParameters(8192) self.sensor.setLatencyTimer(2)
def connect(self, id=None): """Connects to a sensor Use the optional id argument to specify a non-default sensor""" if id == None: id = 0 try: self.sensor = FT.open(id) except FT.DeviceError: print("Error: Device not found") raise self.sensor.setUSBParameters(8192) self.sensor.setLatencyTimer(2)
def openUSB(name_byte_array): for i in range(16): try: usb = ftd2xx.open(i) except: continue if usb.description==name_byte_array: usb.setTimeouts(1000,1000) usb.setUSBParameters(BUFFER_SIZE,BUFFER_SIZE) usb.setBitMode(0xff, 0x40) print('\n opened usb[%d]: %s\n' % (i, str(usb.description, encoding = "utf8"),) ) return True, usb else: usb.close() return False, None
def init(self, iter): print("Tentative de connexion " + str(iter + 1) + "/" + str(MAXITER)) if iter < MAXITER: try: print self.device = ft.open(0) self.device.setBitMode(0xFF, 0x01) # IMPORTANT TO HAVE: This sets up the FTDI device as "Bit Bang" mode. except: time.sleep(4) # Wait 4 seconds self.init(iter + 1) else: print('Impossible de se connecter à la carte relais, vérifier les connexions') sys.exit(0)
def __init__(self): super(MainWindow, self).__init__() self.FTDIsn = self.getFTDIserialNumber() print(self.FTDIsn) self.logFilePointer = open("CalibrationLog_" + self.FTDIsn + ".txt", "w") self.logFilePointer.write("Calibration Run Log File\n") self.initUI() self.setParameters() self.openInstruments() d = ftd.open(0) deviceList = d.getDeviceInfo() self.deviceSerialNum = deviceList['serial'] d.close() self.excelFileName = "SCB_IMON_Cal_" + str( self.deviceSerialNum) + datetime.datetime.now().strftime( "%Y_%m_%d_%H_%M") + ".xlsx" self.workBook = xlsxwriter.Workbook(self.excelFileName) self.SummarySheet = self.workBook.add_worksheet("Summary") self.PlotSheet = self.workBook.add_worksheet("Plots") self.LogSheet = self.workBook.add_worksheet("Log") self.headerCellFormat = self.workBook.add_format() self.headerCellFormat.set_font_size(16) self.headerCellFormat.set_bold() self.logFilePointer.write("FTDI Serial Number " + self.FTDIsn + "\n") self.SummarySheet.write(0, 0, "FTDI S.N.", self.headerCellFormat) self.SummarySheet.write(0, 1, self.FTDIsn) self.SummarySheet.write(0, 2, "DFlash S.N.", self.headerCellFormat) self.SummarySheet.write(0, 4, "FW Version", self.headerCellFormat) self.SummarySheet.write(0, 6, "Register Check", self.headerCellFormat) dflashSN = self.FTDIsn[:-1] self.SummarySheet.write(0, 3, dflashSN) self.SummarySheet.write(1, 0, "Board Product S.N.", self.headerCellFormat) self.SummarySheet.write(1, 2, "Date", self.headerCellFormat) self.doDutInfo = True # print self.flashBoard() version = self.getVersion() print(version[29:41]) self.SummarySheet.write(0, 5, version[29:41])
def device_Info(): try: d = ftd.open(0) # Open first FTDI device di = d.getDeviceInfo() #di = convert_dic(di) dij = json.dumps({ 'description': di['description'].decode('utf-8'), 'serial': di['serial'].decode('utf-8') }) print(dij) except: d.close() return 404 d.close() return dij
def ftdi_open(board_id, channel, desc=None): """opens FTDI device function depending of the current OS""" if OS == 'Linux': return pylibftdi.Device(device_index=board_id, interface_select=channel + 1) elif OS == 'Windows': add = desc.get('location') dev_list = ftdi.listDevices() dev_channel = None for i, d in enumerate(dev_list): if d != b'': if chr(d[-1]) == chr(ord('A') + channel): tmp_dev = ftdi.getDeviceInfoDetail(i) if tmp_dev.get('location') == add + channel: dev_channel = tmp_dev.get('index') else: pass return ftdi.open(dev_channel)
def __init__(self): self.device = None # Setup try: # On Unix systems, we need to manually set the product and vendor IDs ftd.setVIDPID(VID, PID) except AttributeError: # The method is not available on Windows pass # Connect try: # Open the first FTDI device self.device = ftd.open(0) # Get info self.logger.info(self.device.getDeviceInfo()) except ftd.ftd2xx.DeviceError: # Could not open device raise WorkerInterrupt('Could not open device') # Initialize connection if self.device: self.device.setBaudRate(921600) self.device.setFlowControl(ftd.defines.FLOW_NONE, 0, 0) self.device.setDataCharacteristics(ftd.defines.BITS_8, ftd.defines.STOP_BITS_1, ftd.defines.PARITY_NONE) self.device.setTimeouts(2000, 2000) self.device.setLatencyTimer(2) self.device.setUSBParameters(BUFFER_SIZE, BUFFER_SIZE) # Start acquisition self.packet_count = 0 self.time_delta = { '1024Hz': np.timedelta64(int(1e9 / 1024), 'ns'), '256Hz': np.timedelta64(int(1e9 / 256), 'ns'), } self.start() self.time_start = now()
def __init__(self, name_bytes, timeout=2000): self._chunk = 4096 self._usb = None for i in range(16): try: usb = ftd2xx.open(i) except: continue if usb.description == name_bytes: usb.setTimeouts(timeout, timeout) usb.setUSBParameters(self._chunk, self._chunk) usb.setBitMode(0xff, 0x40) print('opened usb[%d]: %s\n' % ( i, str(usb.description, encoding="utf8"), )) self._usb = usb return else: usb.close() raise Exception('Could not open USB device: %s' % str(name_bytes, encoding="utf8"))
def connect(self, iter): print("Tentative de connexion " + str(iter) + "/" + str(MAXITER)) if iter < MAXITER: try: self.device = ft.open(0) self.device.setBitMode( 0xFF, 0x01 ) # IMPORTANT TO HAVE: This sets up the FTDI device as "Bit Bang" mode except Exception as e: if e.message == 'DEVICE_NOT_FOUND': time.sleep(4) # Wait 4 seconds self.connect(iter + 1) else: print(e.message) sys.exit(1) else: print( 'Impossible de se connecter à la carte relais, vérifier les connexions' ) sys.exit(1)
def __open_device(): dev = ftd2xx.open() return dev
def __init__(self, serial=None): if serial is not None: self.dev = ftd2xx.openEx(serial) else: self.dev = ftd2xx.open() self.dev.setTimeouts(read=5000, write=5000)
import ftd2xx as d2xx while True: num_input = raw_input("Enter an integer, GET, or EXIT: ") if num_input == "EXIT": break # These 3 lines of boilerplate are necessary each time you open the device usb = d2xx.open(0) usb.setTimeouts(100, 100) usb.setUSBParameters(640) if num_input == "GET": bytes_received = usb.getQueueStatus() try: data = usb.read(bytes_received) print ord(data[1]) except IndexError: print "No bytes in the transmit queue" else: try: num_int = int(num_input) except ValueError: print "Error: To write to device, enter an integer between 0 and 255. Otherwise, enter GET to read from the device or EXIT to quit." usb.close() continue if num_int < 0 or num_int > 255: print "Error: Enter an integer between 0 and 255" usb.close() continue
def open_device(name): devices = ftd2xx.listDevices() ix = devices.index(name) return ftd2xx.open(dev=ix)
def setUp(self): self.device = ftd2xx.open()
def __init__(self, name, address=0, ver=0, use_internal_trigger=True, mode='master'): from qsweepy.config import get_config import numbers #qtlab stuff Instrument.__init__(self, name, tags=['measure']) # Opening ftd2xx connection (USB-COM dongle) if not isinstance(address, numbers.Integral): address = ftd2xx.listDevices().index(address) print ('opening device') self.h = ftd2xx.open(address) print ('device open') # QTLab stuff self.add_parameter('repetition_period', type=float, flags=Instrument.FLAG_SET | Instrument.FLAG_SOFTGET, minval=2e-9) self.add_function('LoadRAM') self.add_function('Send2CPU') self.add_function('ProgLimit') self.add_function('RamAddrCtrl') self.add_function('SetDAC8') self.add_function('InitDAC8') self.add_function('ProgAutoTrigger') self.add_function('ProgTimer') self.add_function('ProgRepeater') self.add_function('LoadPWL') self.add_function('intToBytes') #self.add_function('SetDAC16Gain') self.add_function('SetDAC16zero') self.add_function('SetDAC16') self.add_function('ProgPulse') self.add_function('SetPulseAmplitude') self.add_function('SendControlWord') self.add_function('InitPulseDacs') self.add_function('SendPacket') self.add_function('set_trigger_repeats') self.add_function('get_trigger_repeats') self.add_function('set_trigger_period') self.add_function('get_trigger_period') self.add_function('set_repetition_period') self.add_function('get_repetition_period') self.add_function('set_trigger_amplitude') self.add_function('get_trigger_amplitude') self.add_function('set_trigger_pulse') self.add_function('get_trigger_pulse') self.add_function('set_waveform') self.add_function('get_waveform') self.add_function('create_delayed_trigger_pulse') self.add_function('get_max_value') self.add_function('get_min_value') self.add_function('get_sample_period') self.add_function('get_sample_dtype') self.add_function('get_max_sample_size') # default driver settings channel_settings = {channel_id:{'on':True, # turn on channel power 'mode': 'ram', # AWG mode: 'ram' - predefined point, 'PWL' - piecewise linear 'filter':False, # turno/off 10 MHz filter (only available for channel 0) 'offset':0, # slow hardware offset (only available for channel 0) 'sw_offset':0, #software offset 'signed':True, # 0 for -8192 to 8191, 1 for 0 to 16383 'continuous_run':False, # enables repetition inside a single AWG pulse sequence for this channel 'reset_enable':False, # enables repetition rate inside a single AWG pulse sequence # for this channel different from 32768 pulse points 'clock_phase':0, # clock phase inverter (1 ns shift) 'delta_ram':0, # points per clock period 'slow':0, # 2e-9 s clock period per data point 'ram_pulse_length':32768, # repetition rate inside a single AWG pulse sequence if 'continuous run' and 'reset enable' is on 'delay':0 # some strange delay } for channel_id in range(7)} self.pulses = {channel_id: [] for channel_id in range(7)} self.channel_settings = channel_settings self.use_internal_trigger = use_internal_trigger # turning on AWG channels (control word) self.ver = ver if ver == 2: self.h.setBitMode(0xff, 0x40) self.h.setUSBParameters(0x10000, 0x10000) self.h.setLatencyTimer(2) self.h.setFlowControl(FT_FLOW_RTS_CTS, 0, 0) is_programmed = self.IsVirtexProgrammed() print ('Virtex is programmed? ', is_programmed) if not is_programmed: if mode=='master': self.ProgVirtex6(filename=get_config()['AWG500_default_firmware']) else: self.ProgVirtex6(filename=get_config()['AWG500_slave_firmware']) self.send_control_word() # setting a single trigger per AWG repeat self.set_trigger_repeats(1) self.set_trigger_period(0) self.set_repetition_period(self.get_max_sample_size()*2e-9) # setting trigger amplitudes for PLS channels #self.trigger_amplitudes = {'PLS5':0xfff0, 'PLS2':0xfff0, 'PLS1':0xfff0} self.trigger_amplitudes = {'PLS5':0x0000, 'PLS2':0x0000, 'PLS1':0x0000} for channel_name, amplitude in zip(self.trigger_amplitudes.keys(), self.trigger_amplitudes.values()): self.set_trigger_amplitude(channel_name, amplitude) # setting trigger pulse form. This is sick shit and it doesn't work as expected. # see documentation for explanation how it should work in principle. #default_trigger_pulse = [0, 4] default_trigger_pulse = self.create_delayed_trigger_pulse(0) self.trigger_pulses = {channel_name:default_trigger_pulse for channel_name in ['SYNC0']}#, 'PLS1', 'PLS2', 'SYNC3', 'SYNC4', 'PLS5']} for channel_name, pulse in zip(self.trigger_pulses.keys(), self.trigger_pulses.values()): self.set_trigger_pulse(channel_name, pulse) # setting default AWG channel settings for channel_id, settings in zip(self.channel_settings.keys(), self.channel_settings.values()): self.set_channel_settings(channel_id, settings)
def testopen(self): self.assert_(isinstance(ftd2xx.open(), ftd2xx.FTD2XX))
def __init__(self,hwser=None): # Find out how many ftd2xx devices are connected to the USB bus numDevices=ftd2xx.createDeviceInfoList() # Check each device to see if either the serial number matches (if given) or the description string is recognized as valid for the class type numMatchingDevices=0 for dev in range(numDevices): detail=ftd2xx.getDeviceInfoDetail(dev) if hwser!=None and detail["serial"]!="" and int(detail["serial"])==hwser: # Get the first device which matches the serial number if given numMatchingDevices+=1 self.device=device=ftd2xx.open(dev) break elif hwser==None and (detail["description"] in self.deviceDescriptionStrings()): # Get the first device which is valid for the given class if no hwser numMatchingDevices+=1 if numMatchingDevices==1: self.device=device=ftd2xx.open(dev) elif dev==numDevices-1 and numMatchingDevices==0: # Raise an exception if no devices were found if hwser!=None: errorStr="Hardware serial number " + str(hwser) + " was not found" else: errorStr="No devices found matching class name " + type(self).__name__ + ". Expand the definition of CLASS_STRING_MAPPING if necessary" raise DeviceNotFoundError, errorStr # Print a warning message if no serial given and multiple devices were found which matched the class type if numMatchingDevices>1 and hwser==None: print(str(numMatchingDevices)+" devices found matching " + type(self).__name__ + "; the first device was opened") # Inititalize the device according to FTD2xx and APT requirements device.setBaudRate(ftd2xx.defines.BAUD_115200) device.setDataCharacteristics(ftd2xx.defines.BITS_8,ftd2xx.defines.STOP_BITS_1,ftd2xx.defines.PARITY_NONE) self.delay() device.purge() self.delay() device.resetDevice() device.setFlowControl(ftd2xx.defines.FLOW_RTS_CTS) device.setTimeouts(c.WRITE_TIMEOUT,c.READ_TIMEOUT) # Check first 2 digits of serial number to see if it's normal type or card/slot type, and build self.channelAddresses as list of (chanID,destAddress) tuples self.channelAddresses=[] if device.serial[0:2] in c.BAY_TYPE_SERIAL_PREFIXES: # Get the device info serNum,model,hwtype,firmwareVer,notes,hwVer,modState,numCh=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO,destID=c.RACK_CONTROLLER_ID)[-1] # Check each bay to see if it's enabled and also request hardware info for bay in range(numCh): bayId=c.ALL_BAYS[bay] self.writeMessage(c.MGMSG_HW_NO_FLASH_PROGRAMMING,destID=bayId) if self.BayUsed(bay): bayInfo=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO,destID=bayId)[-1] self.channelAddresses.append((c.CHANNEL_1,bayId)) else: # Otherwise just build a list of the channel numbers self.writeMessage(c.MGMSG_HW_NO_FLASH_PROGRAMMING,destID=c.GENERIC_USB_ID) serNum,model,hwtype,firmwareVer,notes,hwVer,modState,numCh=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO)[-1] for channel in range(numCh): self.channelAddresses.append((c.ALL_CHANNELS[channel],c.GENERIC_USB_ID)) for channel in range(len(self.channelAddresses)): self.writeMessage(c.MGMSG_MOD_SET_CHANENABLESTATE,1,c.CHAN_ENABLE_STATE_ENABLED,c.RACK_CONTROLLER_ID) self.EnableHWChannel(channel) # Set the controller type self.controllerType=model.replace("\x00","").strip() # Print a message saying we've connected to the device successfuly print("Connected to %s device with serial number %d. Notes about device: %s"%(model.replace('\x00', ''),serNum,notes.replace('\x00', '')))
@author: daukes """ import ftd2xx import time import ftd2xx.defines as fd sn = b'73876440' devices = ftd2xx.listDevices() if not sn in devices: print("No device found. Exiting...") else: ii = devices.index(sn) print("Initializing device...") device = ftd2xx.open(ii) device.setBaudRate(115200) # time.sleep(50/1000) time.sleep(1) device.setDataCharacteristics(fd.BITS_8, fd.STOP_BITS_1, fd.PARITY_NONE) # device.setFlowControl() device.purge(fd.PURGE_RX | fd.PURGE_TX) # time.sleep(50/1000) time.sleep(1) device.resetDevice() time.sleep(1) device.setFlowControl(fd.FLOW_RTS_CTS, 0, 0) device.setRts() print(device.getDeviceInfo()) device.write(b'\x05\x00\x00\x00\x11\x01') time.sleep(.1)
def __init__(self): super(MainWindow, self).__init__() self.FTDIsn = "" self.FTDIsn = self.getFTDIserialNumber() print self.FTDIsn self.logFilePointer = open("CFTAC_Log_" + self.FTDIsn + ".txt", "w") self.logFilePointer.write("CFTAC Run Log File\n") dialog = dutInfoDialog.DutInfoDialog() dialog.setWindowModality(Qt.ApplicationModal) dialog.exec_() self.configID, self.probeType, self.productSN, self.runNotes = dialog.returnInfo( ) self.configFileName = QFileDialog.getOpenFileName( self, 'Open file', 'C:\\Users\\v-stpur\\Documents\\CFTAC_Python_Port_Apps_MultiChannel', "Excel files (*.xlsx)") self.logFilePointer.write("Config File Name: " + str(self.configFileName[0]) + "\n") print "Filename is: " + str(self.configFileName[0]) self.initUI() self.openInstruments() d = ftd.open(0) deviceList = d.getDeviceInfo() self.deviceSerialNum = deviceList['serial'] self.deviceSerialNum = "" d.close() self.excelFileName = "CFTAC_Output_" + self.deviceSerialNum + datetime.datetime.now( ).strftime("%Y_%m_%d_%H_%M") + ".xlsx" #Create the output file here so we can put the summary page on it #then in the timer thread open the config file and create additional tabs on the output file self.workBook = Workbook() self.SummarySheet = self.workBook.active self.SummarySheet.title = "Summary" headerCellFormat = NamedStyle(name="Header") headerCellFormat.font = Font(bold=True, size=16) self.workBook.add_named_style(headerCellFormat) self.logFilePointer.write("FTDI Serial Number " + self.FTDIsn + "\n") self.SummarySheet['A1'].style = headerCellFormat self.SummarySheet['A2'].style = headerCellFormat self.SummarySheet['A3'].style = headerCellFormat self.SummarySheet['A5'].style = headerCellFormat self.SummarySheet['C1'].style = headerCellFormat self.SummarySheet['C2'].style = headerCellFormat self.SummarySheet['E1'].style = headerCellFormat self.SummarySheet.cell(1, 1, "FTDI S.N.") self.SummarySheet.cell(1, 2, self.FTDIsn) self.SummarySheet.cell(1, 5, "FW Version") dflashSN = self.FTDIsn[:-1] self.SummarySheet.cell(1, 4, dflashSN) self.SummarySheet.cell(2, 1, "Product S.N.") self.SummarySheet.cell(2, 2, self.pcbaSN) self.SummarySheet.cell(2, 3, "Date") self.SummarySheet.cell( 2, 4, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.SummarySheet.cell(3, 1, "Configuration File") # self.SummarySheet.cell(3, 2, self.configFileName) self.SummarySheet.cell(4, 1, "Probe Type") self.SummarySheet.cell(4, 2, self.probeType) self.SummarySheet.cell(4, 3, "Run Notes") self.SummarySheet.cell(4, 4, self.runNotes) version = self.getVersion() print version[29:41] self.SummarySheet.cell(1, 6, version[29:41])
def connect(self): time = 0 while True: try: # Is a simp present. # This takes too long... devices = self._find_some_simps() # Did I catch a simp? if (len(devices) == 0): raise Exception('Cound not find a SIMPS ATE device. Make sure the FTDI chip is programmed and the D2XX driver is installed.') # We are going to assume that there is only one simp per PC right now. if (len(devices) != 1): raise Exception('Too many simps for this software to handle.') # Lets make a connection to the simp. self.device = ftd2xx.open(devices[0]['index']) # Reset Device self.device.resetDevice() # Set Timeouts #self.device.setTimeouts(500, 500) # Set Latency Time - 2ms #self.device.setLatencyTimer(2) # Set USB Parameters - #self.device.setUSBParameters(in_tx_size, out_tx_size=0) # If we wanted to so the synchronus interface, #self.device.setBitMode(mask, enable) # Set Flow Control - 0x0100, RTS-CTS #self.device.setFlowControl(FLOW_RTS_CTS) # Purge Buffers #self.device.purge(PURGE_RX + PURGE_TX) # FT_Set_DTR #self.device.setDtr() # FT_set_RTS #self.device.setRts() except: # We failed to connect to the device. if (self.connect_timeout == None): # There is not connection timeout, so re-raise the exception. raise else: if (time >= self.connect_timeout): # Re-raise the exception if we are over the allowed waiting time. raise else: # Wait before retrying. # Note: This will probably take longer than wanted. # Should probably change to time.now() sleep(0.25) time = time + 0.25 else: # The connection was successful, so break the loop. break
import time import array import ftd2xx import pydyn.dynamixel.packet print('Loading the robot from serial bus...') #port = pydyn.dynamixel.get_available_ports()[0] #print('Port found: {}'.format(port)) #io = pydyn.dynamixel.io.DynamixelIO(port, timeout = 0.1, baudrate = 1000000) serial = ftd2xx.open() serial.setLatencyTimer(2) serial.setBaudRate(1000000) serial.setTimeouts(200, 200) # send_data = [] # for i in [1]: def send(i, pad=False): packet = pydyn.dynamixel.packet.DynamixelReadDataPacket(i, 'PRESENT_POS_SPEED_LOAD') send_data = packet.to_bytes() # if pad: # send_data += array.array('B', [255]*(62-len(send_data))).tostring() #print (len(send_data), [ord(c) for c in send_data]) assert serial.write(send_data) == len(send_data) #io._serial.flushInput() data = serial.read(12) odata = [ord(c) for c in data]