def InitializeDevice(self):
        # Open the first device we find.
        self.dev = ok.okCFrontPanel()
        self.pll = ok.okCPLL22150()
        if (self.dev.NoError != self.dev.OpenBySerial("")):
            print("A device could not be opened. Is one connected?")
            return(False)

        # Get some general information about the device.
        self.devInfo = ok.okTDeviceInfo()
        if (self.dev.NoError != self.dev.GetDeviceInfo(self.devInfo)):
            print("Unable to retrieve device information.")
            return(False)
        print("         Product: {}".format(self.devInfo.productName))
        print("Firmware version: {}.{}".format(self.devInfo.deviceMajorVersion, self.devInfo.deviceMinorVersion))
        print("   Serial Number: {}".format(self.devInfo.serialNumber))
        print("       Device ID: {}".format(self.devInfo.deviceID.split('\0')[0]))

        self.dev.LoadDefaultPLLConfiguration()

        # Download the configuration file.
        if self.ConfigFile == '':
            if self.devInfo.productName == 'XEM6002-LX9':
                self.ConfigFile = r'..\okwmb-xem6002.bit'
        if (self.dev.NoError != self.dev.ConfigureFPGA(self.ConfigFile)):
            return(False)

        # Check for FrontPanel support in the FPGA configuration.
        if (False == self.dev.IsFrontPanelEnabled()):
            return(False)
        
        # Initialisation completed successfully
        return(True)
Beispiel #2
0
	def InitializeDevice(self):
		# Open the first device we find.
		self.xem = ok.okCFrontPanel()
		if (self.xem.NoError != self.xem.OpenBySerial("")):
			print("[INITIAL]", "A device could not be opened.  Is one connected?")
			return(False)

		# Get some general information about the device.
		self.devInfo = ok.okTDeviceInfo()
		if (self.xem.NoError != self.xem.GetDeviceInfo(self.devInfo)):
			print("[INITIAL]", "Unable to retrieve device information.")
			return(False)
		print("[INITIAL]", "         Product: ", self.devInfo.productName)
		print("[INITIAL]", "Firmware version: %d.%d" % (self.devInfo.deviceMajorVersion, self.devInfo.deviceMinorVersion))
		print("[INITIAL]", "   Serial Number: %s" % self.devInfo.serialNumber)
		print("[INITIAL]", "       Device ID: %s" % self.devInfo.deviceID)
		
		self.xem.LoadDefaultPLLConfiguration()

		# Download the configuration file.
		if (self.xem.NoError != self.xem.ConfigureFPGA(bit_directory)):
			print("[INITIAL]", "FPGA configuration failed.")
			return(False)

		# Check for FrontPanel support in the FPGA configuration.
		if (False == self.xem.IsFrontPanelEnabled()):
			print("[INITIAL]", "FrontPanel support is not available.")
			return(False)
		
		print("[INITIAL]", "FrontPanel support is available.")
		return(True)
Beispiel #3
0
	def InitializeDevice(self):
		# Open the first device we find.
		self.xem = ok.okCFrontPanel()
		if (self.xem.NoError != self.xem.OpenBySerial("")):
			print ("A device could not be opened.  Is one connected?")
			return(False)

		# Get some general information about the device.
		self.devInfo = ok.okTDeviceInfo()
		if (self.xem.NoError != self.xem.GetDeviceInfo(self.devInfo)):
			print ("Unable to retrieve device information.")
			return(False)
		print("         Product: " + self.devInfo.productName)
		print("Firmware version: %d.%d" % (self.devInfo.deviceMajorVersion, self.devInfo.deviceMinorVersion))
		print("   Serial Number: %s" % self.devInfo.serialNumber)
		print("       Device ID: %s" % self.devInfo.deviceID)

		# Download the configuration file.
		if (self.xem.NoError != self.xem.ConfigureFPGA("ok_XLA.bit")):
			print ("FPGA configuration failed.")
			return(False)

		# Check for FrontPanel support in the FPGA configuration.
		if (False == self.xem.IsFrontPanelEnabled()):
			print ("FrontPanel support is not available.")
			return(False)

		print ("FrontPanel support is available.")
		return(True)
Beispiel #4
0
 def open_by_serial(self, c, serial):
     if serial not in self._open_xems:
         fp = ok.okCFrontPanel()
         fp.GetDeviceCount()
         success = fp.OpenBySerial(serial)
         fp._lock = DeferredLock()
         self._open_xems[serial] = fp
     return serial
 def _get_available_interfaces(self):
     open = self._get_open_interfaces()
     available_but_not_open = []
     
     fp = ok.okCFrontPanel()
     device_count = fp.GetDeviceCount()
     for i in range(device_count):
         serial_number = fp.GetDeviceListSerial(i)
         available_but_not_open.append(serial_number)
     
     return open + available_but_not_open
 def InitializeDevice(self):
     self.xem = ok.okCFrontPanel()
     if self.xem.NoError != self.xem.OpenBySerial(self.xem.GetSerialNumber()):
         print 1
         return False
     self.xem.LoadDefaultPLLConfiguration()
     if self.xem.NoError != self.xem.ConfigureFPGA("USART_RS_232/usart_fifos_manager_tm.bit"):
         print 2
         return False
     if self.xem.IsFrontPanelEnabled() == False:
         print 3
         return False
     return True
Beispiel #7
0
    def refresh_available_interfaces(self):
        for device_id, device in self.interfaces.items():
            try:
                device.GetDeviceID()
            except:
                print 'removing interface {}'.format(device_id)
                del self.interfaces[device_id]

        open_serials = [
            interface.GetSerialNumber()
            for interface in self.interfaces.values()
        ]
        fp = ok.okCFrontPanel()
        device_count = fp.GetDeviceCount()
        for i in range(device_count):
            serial = fp.GetDeviceListSerial(i)
            if serial not in open_serials:
                tmp = ok.okCFrontPanel()
                tmp.OpenBySerial(serial)
                device_id = tmp.GetDeviceID()
                tmp.LoadDefaultPLLConfiguration()
                self.interfaces[device_id] = tmp
Beispiel #8
0
	def __init__(self):
		self.xem = ok.okCFrontPanel()
		if (self.xem.NoError != self.xem.OpenBySerial("")):
			print ("A device could not be opened.  Is one connected?")
			#return(False)

		devInfo = ok.okTDeviceInfo()
		if (self.xem.NoError != self.xem.GetDeviceInfo(devInfo)):
			print ("Unable to retrieve device information.")
			exit
		print("Got device: " + devInfo.productName)

		if (self.xem.NoError != self.xem.ConfigureFPGA("cavity.bit")):
			print ("FPGA configuration failed.")
			exit
def main():
    global FP
    FP = ok.okCFrontPanel()
    devs = enumerate_devices()
    if len(devs) == 0:
        return

    serial = FP.GetDeviceListSerial(0)
    if FP.IsOpen():
        FP.Close()
    FP.OpenBySerial(serial)
    filename = ("/home/caleb/Sources/Telescope_Project/VFPIX-telescope-Code/"
                "DAQ_Firmware/output_files/daq_firmware.rbf")
    program_device(filename)
    test2(False)
    FP.Close()
Beispiel #10
0
    def init(self):
        global h5py
        import labscript_utils.h5_lock, h5py
        # global serial; import serial
        global time
        import time
        global zprocess
        import zprocess
        global ok
        import ok  # OpalKelly library

        # check the import worked correctly
        # This handles the difference between v4 and v5 of front panel I think
        if not hasattr(ok, 'okCFrontPanel'):
            from ok import ok

        global numpy
        import numpy

        self.all_waits_finished = zprocess.Event('all_waits_finished',
                                                 type='post')
        self.wait_durations_analysed = zprocess.Event(
            'wait_durations_analysed', type='post')
        self.wait_completed = zprocess.Event('wait_completed', type='post')
        self.current_wait = 0
        self.wait_table = None
        self.measured_waits = None
        self.h5_file = None

        self.current_value = 0

        # Initialise connection to OPAL KELLY Board
        self.dev = ok.okCFrontPanel()
        if PY2:
            self.serial = bytes(self.serial)
        assert self.dev.OpenBySerial(self.serial) == self.dev.NoError

        try:
            assert self.dev.IsFrontPanelEnabled()
        except AssertionError:
            # Flash the FPGA bit file
            self.flash_FPGA()

        # ensure the FPGA's state machine is deactivated
        assert self.dev.ActivateTriggerIn(0x40, 1) == self.dev.NoError
Beispiel #11
0
    def InitializeDevice(self):
        print("---- Opal Kelly ---- PipeTest Application vX.Y ----\n");
        # Open the first device we find.
        self.xem = ok.okCFrontPanel()
        if (self.xem.NoError != self.xem.OpenBySerial("")):
            print("A device could not be opened.  Is one connected?")
            return(False)

        # Get some general information about the device.
        self.devInfo = ok.okTDeviceInfo()
        if (self.xem.NoError != self.xem.GetDeviceInfo(self.devInfo)):
            print("Unable to retrieve device information.")
            return(False)
        print("         Product: {}".format(self.devInfo.productName))
        print("Firmware version: {}.{}".format(self.devInfo.deviceMajorVersion, self.devInfo.deviceMinorVersion))
        print("   Serial Number: {}".format(self.devInfo.serialNumber))
        print("       Device ID: {}".format(self.devInfo.deviceID.split('\0')[0]))

        self.xem.LoadDefaultPLLConfiguration()

        # Download the configuration file.
        if self.devInfo.productName == 'XEM6002-LX9':
            config_file_name = '..\pipetest-xem6002.bit'
        else:
            config_file_name = ''
        if (self.xem.NoError != self.xem.ConfigureFPGA(config_file_name)):
            print("FPGA configuration failed.")
            return(False)

        # Check for FrontPanel support in the FPGA configuration.
        if (False == self.xem.IsFrontPanelEnabled()):
            print("FrontPanel support is not available.")
            return(False)
        print("FrontPanel support is available.")
        
        # Initialisation completed successfully
        return(True)
Beispiel #12
0
    args.clkout0phase = 180000

    args.getdata = 1
    args.datasize = 1000
    args.ignoreframes = 10
    args.numimage = 3
    args.outputfile = 'rawdata\\dat'

    args



    error_list = []

    # FIND AND OPEN THE OPAL KELLY (CAN ONLY RECOGNIZE SINGLE DEVICE)
    device = ok.okCFrontPanel()
    device.OpenBySerial(device.GetDeviceListSerial(0))

    # FLASH DEVICE
    if args.flash == 1:
        flerr = device.ConfigureFPGA(args.flashfile)
        print('     Flashing device with error code ', flerr)

    if device.IsFrontPanelEnabled(): # IsFrontPanelEnabled returns true if FrontPanel is detected.
        #print("     FrontPanel host interface enabled.")
        pass
    else:
        sys.stderr.write("     FrontPanel host interface not detected.")


# EXECUTION ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
import time  # time related library
import sys  # system related library
ok_loc = 'C:\\Program Files\\Opal Kelly\\FrontPanelUSB\\API\\Python\\3.6\\x64'
sys.path.append(ok_loc)  # add the path of the OK library
import ok  # OpalKelly library
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import threading
import cv2

#%%
# Define FrontPanel device variable, open USB communication and
# load the bit file in the FPGA
dev = ok.okCFrontPanel()  # define a device for FrontPanel communication
SerialStatus = dev.OpenBySerial("")  # open USB communicaiton with the OK board
ConfigStatus = dev.ConfigureFPGA("BTPipeExample.bit")
# Configure the FPGA with this bit file

# Check if FrontPanel is initialized correctly and if the bit file is loaded.
# Otherwise terminate the program
print("----------------------------------------------------")
if SerialStatus == 0:
    print("FrontPanel host interface was successfully initialized.")
else:
    print("FrontPanel host interface not detected. The error code number is:" +
          str(int(SerialStatus)))
    print("Exiting the program.")
    sys.exit()
Beispiel #14
0
 def get_device_count(self, c):
     fp = ok.okCFrontPanel()
     return fp.GetDeviceCount()
Beispiel #15
0
    def __init__(self, parent=None, ident=-1):
        wx.Frame.__init__(
            self, parent, ident, 'OSC1Lite Stimulate GUI v' + __version__ +
            '  ** CLICK DISCONNECT BEFORE TURNING OFF BOARD SWITCH **')
        self._dev = ok.okCFrontPanel()
        self.device = None
        self.devices = {}

        self.board_relative_controls = []

        p = wx.Panel(self, -1)

        # Setup frame
        setup_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, p, 'Setup')
        self.device_choice = wx.Choice(p,
                                       -1,
                                       choices=['[No connected device]'])
        self.device_choice.SetSelection(0)
        self.device_choice.SetSize(self.device_choice.GetBestSize())
        self.connect_button = wx.Button(p, -1, 'Connect')
        self.connect_button.Disable()
        self.connect_button.Bind(
            wx.EVT_BUTTON,
            lambda _: threading.Thread(target=self.on_connect_worker).start())
        threading.Thread(target=self.daemon, daemon=True).start()
        setup_sizer.Add(
            LabeledCtrl(self.device_choice, p, -1, 'Select your OSC1Lite'), 0,
            wx.EXPAND | wx.ALL, 3)
        setup_sizer.AddStretchSpacer(1)
        setup_sizer.Add(self.connect_button, 0, wx.EXPAND | wx.ALL, 3)

        left_box = wx.BoxSizer(wx.VERTICAL)
        left_box.Add(setup_sizer, 0, wx.EXPAND)

        # Config frame
        config_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, p,
                                         'Waveform and Channel Config')
        config_sizer.AddStretchSpacer(1)
        save_config_button = wx.Button(p, -1, 'Save config to file')
        save_config_button.Bind(wx.EVT_BUTTON, self.on_save_config)
        config_sizer.Add(save_config_button, wx.SizerFlags().Expand())
        config_sizer.AddStretchSpacer(1)
        load_config_button = wx.Button(p, -1, 'Load config from file')
        load_config_button.Bind(wx.EVT_BUTTON, self.on_load_config)
        config_sizer.Add(load_config_button, wx.SizerFlags().Expand())
        config_sizer.AddStretchSpacer(1)
        self.board_relative_controls.extend(
            (save_config_button, load_config_button))

        left_box.Add(config_sizer, wx.SizerFlags().Expand())
        left_box.AddSpacer(50)

        self.wfm = WaveformManager(p, self)
        left_box.Add(self.wfm, 1, wx.EXPAND)

        channel_panel = wx.StaticBoxSizer(wx.VERTICAL, p)
        channel_box = wx.FlexGridSizer(8, 5, 5)
        channel_box.Add(wx.StaticText(p, -1, 'Channel #'), 0, wx.ALIGN_CENTER)
        channel_box.Add(wx.StaticText(p, -1, 'Waveform'), 0, wx.ALIGN_CENTER)
        channel_box.Add(wx.StaticText(p, -1, 'Trigger Source'), 0,
                        wx.ALIGN_CENTER)
        channel_box.Add(wx.StaticText(p, -1, 'Mode'), 0, wx.ALIGN_CENTER)
        channel_box.AddSpacer(0)
        channel_box.Add(wx.StaticText(p, -1, 'PC Trigger'), 0, wx.ALIGN_CENTER)
        channel_box.Add(wx.StaticText(p, -1, 'Trigger Out'), 0,
                        wx.ALIGN_CENTER)
        channel_box.Add(wx.StaticText(p, -1, 'Status'), 0, wx.ALIGN_CENTER)
        channels_ui = []
        channel_box.AddGrowableCol(7, 1)
        for i in range(12):

            if oscgui_config['Channel']['order'] == 'shank':
                ch = (7, 2, 8, 0, 6, 1, 10, 5, 11, 3, 9, 4)[i]
                channel_label = wx.StaticText(
                    p, -1, 'S%dL%d' % (i // 3 + 1, i % 3 + 1))
            else:
                ch = i
                channel_label = wx.StaticText(p, -1, 'Channel %d' % i)
            channel_box.Add(channel_label, 0, wx.ALIGN_CENTER)

            waveform_choice = wx.Choice(
                p, -1, choices=['Waveform %d' % (x + 1) for x in range(4)])
            waveform_choice.SetSelection(0)
            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(waveform_choice, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND)

            trigger_choice = wx.Choice(
                p, -1, choices=['PC trigger', 'External trigger'])
            trigger_choice.SetSelection(0)

            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(trigger_choice, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND)

            continuous_toggle = wx.ToggleButton(p, -1, 'One-shot')
            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(continuous_toggle, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND)

            stop_button = wx.Button(p, -1, 'Enable', style=wx.BU_EXACTFIT)
            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(stop_button, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND)

            trigger_button = wx.Button(p, -1, 'Trigger', style=wx.BU_EXACTFIT)
            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(trigger_button, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND)

            trigger_out_check = wx.CheckBox(p, -1)
            trigger_out_check.Bind(wx.EVT_CHECKBOX, self.on_trigger_out)
            channel_box.Add(trigger_out_check, 0, wx.ALIGN_CENTER)

            status_text = wx.TextCtrl(p,
                                      -1,
                                      'Board not connected',
                                      style=wx.TE_READONLY)
            wrap_box = wx.BoxSizer(wx.HORIZONTAL)
            wrap_box.Add(status_text, 1, wx.ALIGN_CENTER_VERTICAL)
            channel_box.Add(wrap_box, 0, wx.EXPAND | wx.LEFT, 5)

            channel = ChannelCtrl(ch, channel_label, waveform_choice,
                                  trigger_choice, continuous_toggle,
                                  trigger_button, stop_button,
                                  trigger_out_check, status_text, self)
            channel.on_disconnect()
            channels_ui.append(channel)
            channel_box.AddGrowableRow(i, 1)
        if oscgui_config['Channel']['order'] == 'shank':
            self.channels_ui = [
                channels_ui[x] for x in (3, 5, 1, 9, 11, 7, 4, 0, 2, 10, 6, 8)
            ]
        else:
            self.channels_ui = channels_ui
        channel_panel.Add(channel_box, 1, wx.EXPAND)

        right_box = wx.BoxSizer(wx.VERTICAL)
        right_box.Add(channel_panel, 0, wx.EXPAND | wx.BOTTOM, 5)

        extra_buttons = wx.BoxSizer(wx.HORIZONTAL)

        if oscgui_config['Waveform']['realtime_update'] != 'yes':
            update_all = wx.Button(p, -1, 'Update all channel parameters')
            update_all.SetToolTip(
                'This will update all waveform parameters, '
                'trigger source, and trigger mode for all modified channel(s).'
                '\nModified channel(s) are marked with asterisk.')
            update_all.Bind(wx.EVT_BUTTON, self.on_update)
            extra_buttons.Add(update_all)
            self.board_relative_controls.append(update_all)

        enable_all = wx.Button(p, -1, 'Enable All')
        enable_all.Bind(wx.EVT_BUTTON,
                        lambda _: self.device.set_enable(range(12), True))
        extra_buttons.Add(enable_all)
        disable_all = wx.Button(p, -1, 'Disable All')
        disable_all.Bind(wx.EVT_BUTTON,
                         lambda _: self.device.set_enable(range(12), False))
        extra_buttons.Add(disable_all)
        trigger_all = wx.Button(p, -1, 'Trigger All')
        trigger_all.Bind(wx.EVT_BUTTON,
                         lambda _: self.device.trigger_channel(range(12)))
        extra_buttons.Add(trigger_all)
        self.board_relative_controls.extend(
            (trigger_all, enable_all, disable_all))
        right_box.Add(extra_buttons, 0, wx.EXPAND | wx.BOTTOM, 50)

        log_text = wx.TextCtrl(p, -1, style=wx.TE_MULTILINE | wx.TE_READONLY)
        sh = logging.StreamHandler(log_text)
        sh.setLevel(logging.INFO)
        self.formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        sh.setFormatter(self.formatter)
        logging.getLogger().addHandler(sh)
        log_box = wx.StaticBoxSizer(wx.VERTICAL, p, 'Log')
        log_box.Add(log_text, 1, wx.EXPAND)

        log_options_sizer = wx.BoxSizer(wx.HORIZONTAL)
        log_options_sizer.AddStretchSpacer(1)
        save_log_checkbox = wx.CheckBox(p, -1, 'Save log to file')
        save_log_checkbox.Bind(wx.EVT_CHECKBOX, self.on_save_log)

        if oscgui_config['OSCGUI']['save_log_to_file'] == 'yes':
            save_log_checkbox.SetValue(True)
            self.log_fh = logging.FileHandler(
                time.strftime('oscgui-%Y%m%d.log'), delay=True)
            self.log_fh.setLevel(logging.INFO)
            self.log_fh.setFormatter(self.formatter)
            logging.getLogger().addHandler(self.log_fh)
        else:
            self.log_fh = None
        clear_log_button = wx.Button(p, -1, 'Clear Log')
        clear_log_button.Bind(wx.EVT_BUTTON, lambda _: log_text.Clear())
        log_options_sizer.Add(save_log_checkbox, wx.SizerFlags().Expand())
        log_options_sizer.Add(clear_log_button, wx.SizerFlags().Expand())
        log_box.Add(log_options_sizer, wx.SizerFlags().Expand())
        right_box.Add(log_box, 1, wx.EXPAND)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(left_box, 0, wx.EXPAND | wx.ALL, 5)
        box.AddSpacer(50)
        box.Add(right_box, 1, wx.EXPAND | wx.ALL, 5)

        for x in self.board_relative_controls:
            x.Disable()

        p.SetSizerAndFit(box)
        self.Fit()
        self.Bind(wx.EVT_CLOSE, self.on_close)
    def __init__(self, flash, reset, reprogpll, parseenable, saveenable,
                 getdata, npix, bitfile, rstcode, fpgaSwitches, clkdiv, duty,
                 phase, flen, fignore, fnum, inum, sdir, sname):

        fnum = int(fnum)
        fignore = int(fignore)
        npix = int(npix)

        # FIND AND OPEN THE OPAL KELLY (CAN ONLY RECOGNIZE SINGLE DEVICE) ----------- ----------- ----------- ----------- -----------
        device = ok.okCFrontPanel()
        device.OpenBySerial(device.GetDeviceListSerial(0))

        # FLASH DEVICE
        if flash == 1:
            flerr = device.ConfigureFPGA(bitfile)
            print('     Flashing device with error code ', flerr)

        if device.IsFrontPanelEnabled(
        ):  # IsFrontPanelEnabled returns true if FrontPanel is detected.
            # print("     FrontPanel host interface enabled.")
            pass
        else:
            sys.stderr.write("     FrontPanel host interface not detected.")

        # INITIALIZE FPGA ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
        error_list = []
        # RESET EVERYTHING
        if reset == 1:
            # print('     Fully resetting device')
            error_list.append(device.SetWireInValue(0x00, int(rstcode)))
            device.UpdateWireIns()
            time.sleep(0.5)
            # set everything to rest
            device.SetWireInValue(0x00, int(0x00000000))
            device.UpdateWireIns()

        # WIREINS
        # device.SetWireInValue(0x01, int(ep01wire)) #not used
        device.SetWireInValue(0x02, int(flen))
        # device.SetWireInValue(0x03, int(ep03wire))
        device.SetWireInValue(0x04, int(clkdiv))
        device.UpdateWireIns()

        # REPROGRAM PLL
        if reprogpll == 1:
            device.SetWireInValue(0x05, int(phase))
            device.SetWireInValue(0x06, int(duty))
            # device.SetWireInValue(0x07, int(args.clkout1phase))
            # device.SetWireInValue(0x08, int(args.clkout1duty))
            # device.SetWireInValue(0x09, int(args.clkout2phase))
            # device.SetWireInValue(0x10, int(args.clkout2duty))
            # device.SetWireInValue(0x14, int(args.clkout3phase))
            # device.SetWireInValue(0x15, int(args.clkout3duty))
            device.UpdateWireIns()
            trigerror = device.ActivateTriggerIn(0x40, 0)

        device.UpdateWireOuts()
        statusWire = device.GetWireOutValue(0x24)
        print('     PLL reprogrammed. Status is ', statusWire)

        # Initialize data
        self.img = np.zeros(npix, dtype=np.uint64)
        self.scatt = np.zeros(fnum * npix, dtype=np.uint8)
        self.goodframes = 0

        # START THE FSM ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
        device.SetWireInValue(0x00, int(fpgaSwitches, 2))
        device.UpdateWireIns()

        # COLLECT DATA
        if getdata:

            BlockSize = 256  # in bytes, important to be the same as in the VHDL code otherwise data could be different
            inum = int(inum)
            # device.UpdateWireOuts()
            # MemoryCount = device.GetWireOutValue(0x26)
            # print('     Current memory count is: %d ' % MemoryCount)

            timestamp = np.zeros(inum)
            ts0 = time.time()
            for i in range(0, inum):

                device.UpdateWireOuts()
                MemoryCount = device.GetWireOutValue(0x26)
                data_out = bytearray((fnum + fignore) * 1024)  # Bytes
                TransferSize = len(data_out)
                # print('     Now transferring {} KB of data from FPGA to PC'.format(TransferSize))
                # print('status 1')

                while MemoryCount < TransferSize:  # /8
                    device.UpdateWireOuts()
                    MemoryCount = device.GetWireOutValue(0x26)
                    # time.sleep(0.001)  # It takes 1 second to fill up the memory to 64MB, so it is useless to check 100000x per second
                    # print('status 2: memory count = %f' % MemoryCount)

                if MemoryCount >= TransferSize:  # /8
                    code = device.ReadFromBlockPipeOut(0xa0, BlockSize,
                                                       data_out)
                    # print('status 3: memory count = %f' % MemoryCount)
                    timestamp[i] = time.time() - ts0
                    print('     timestamp: for frame %i is: %f sec' %
                          (i, timestamp[i]))

                    if code == TransferSize:
                        # #save readout data into bytearray
                        # print('     TransferSize match. Data Retrieved: %.1f kB(frames)' % float(int(code)/1024))
                        # with open(args.outputfile + '_img_' + str(i), 'wb') as f:
                        #     f.write(data_out)
                        #     # print('status 4')
                        # with open(args.outputfile + '_timestamp', 'wb') as f:
                        #     f.write(timestamp)

                        if parseenable:
                            # parse without saving rawdata. only save resulting images.
                            [self.img, self.scatt,
                             self.goodframes] = parse_bytearray.ParseBytearray(
                                 npix, fnum, fignore, data_out).get_data()
                            # save parsed data to files
                            if saveenable:
                                with open(
                                        sdir + '\\' + sname + '_parsedraw_' +
                                        str(i), 'wb') as f:
                                    f.write(self.scatt)
                                with open(
                                        sdir + '\\' + sname + '_parsedflat_' +
                                        str(i) + 'flat', 'wb') as f:
                                    f.write(self.img)
                        else:
                            # save raw data to files
                            if saveenable:
                                with open(
                                        sdir + '\\' + sname + '_unparsed_' +
                                        str(i), 'wb') as f:
                                    f.write(data_out)

                    else:
                        print(
                            '     TransferSize doesnt match. Amount of data retrieved from Pipe Out is %d Bytes'
                            % code)
                        print('     Do not write file!')
                        sys.stderr.write(
                            "     Data was not retrieved correctly. Error code returned is %d Bytes"
                            % code)
                        # print('status 5')

                    # reset RAM
                    # print('     Current memory count is: %d ' % MemoryCount)
                    device.SetWireInValue(0x00, int(0x00000007))
                    device.UpdateWireIns()
                    device.SetWireInValue(0x00, int(fpgaSwitches, 2))
                    device.UpdateWireIns()

                    device.UpdateWireOuts()
                    MemoryCount = device.GetWireOutValue(0x26)
Beispiel #17
0
 def get_device_list_serial(self, c, num):
     fp = ok.okCFrontPanel()
     fp.GetDeviceCount()
     return fp.GetDeviceListSerial(num)
 def __init__(self, settings=example_settings):
     self.xem = ok.okCFrontPanel()
     self.initializeDevice()
     self.init_experiment(settings)
     self.num_channels = settings['num_channels']
     self.capture_duration = settings['capture_duration']
Beispiel #19
0
    def __init__(self, enflash, enreset, enreprogpll, interrupted, npix,
                 bitfile, rstcode, fpgaSwitches, clkdiv, duty, phase, flen,
                 fignore, fnum, inum, sdir, sname, tsdir):
        # expected data types are..
        # bool for: enflash, enreset, enreprogpll
        # str for: bitfile, rstcode, fpgaSwitches
        # int for: flen, clkdiv, phase, duty

        # FIND AND OPEN THE OPAL KELLY (CAN ONLY RECOGNIZE SINGLE DEVICE) ----------- ----------- ----------- ----------
        self.device = ok.okCFrontPanel()
        self.device.OpenBySerial(self.device.GetDeviceListSerial(0))

        # FLASH DEVICE
        if enflash == 1:
            flerr = self.device.ConfigureFPGA(bitfile)
            if flerr == 0:
                print('     Opal Kelly Flash Successful')
            else:
                print('     Opal Kelly Flash with error code ', flerr)

            if self.device.IsFrontPanelEnabled(
            ):  # IsFrontPanelEnabled returns true if FrontPanel is detected.
                print("     FrontPanel host interface enabled.")
                pass
            else:
                sys.stderr.write(
                    "     FrontPanel host interface NOT detected.")

        # RESET EVERYTHING
        error_list = []
        if enreset == 1:
            # print('     Fully resetting device')
            error_list.append(self.device.SetWireInValue(0x00, int(rstcode)))
            self.device.UpdateWireIns()
            time.sleep(0.5)
            # set everything to rest
            self.device.SetWireInValue(0x00, int(0x00000000))
            self.device.UpdateWireIns()

            # WIREINS
            # self.device.SetWireInValue(0x01, int(ep01wire)) #not used
            self.device.SetWireInValue(0x02, flen)
            # self.device.SetWireInValue(0x03, int(ep03wire))
            self.device.SetWireInValue(0x04, clkdiv)
            self.device.UpdateWireIns()

        # REPROGRAM PLL
        if enreprogpll == 1:
            self.device.SetWireInValue(0x05, phase)
            self.device.SetWireInValue(0x06, duty)
            # self.device.SetWireInValue(0x07, int(args.clkout1phase))
            # self.device.SetWireInValue(0x08, int(args.clkout1duty))
            # self.device.SetWireInValue(0x09, int(args.clkout2phase))
            # self.device.SetWireInValue(0x10, int(args.clkout2duty))
            # self.device.SetWireInValue(0x14, int(args.clkout3phase))
            # self.device.SetWireInValue(0x15, int(args.clkout3duty))
            self.device.UpdateWireIns()
            trigerror = self.device.ActivateTriggerIn(0x40, 0)

            self.device.UpdateWireOuts()
            statusWire = self.device.GetWireOutValue(0x24)
            print('     PLL reprogrammed. Status is ', statusWire)

        # START THE FSM
        self.device.SetWireInValue(0x00, int(fpgaSwitches, 2))
        self.device.UpdateWireIns()

        ###############################################################################################################
        # Data Acquisition
        timestamp = np.zeros(inum)
        ts0 = time.time()
        # interrupted = False

        for ii in range(0, inum):

            if interrupted:
                break

            # Initialize data
            # img = np.zeros(npix, dtype=np.uint64)
            # scatt = np.zeros(fnum * npix, dtype=np.uint8)
            # goodframes = 0

            self.device.UpdateWireOuts()
            MemoryCount = self.device.GetWireOutValue(0x26)
            data_out = bytearray((fnum + fignore) * 1024)  # Bytes
            TransferSize = len(data_out)
            # print('     Now transferring {} KB of data from FPGA to PC'.format(TransferSize))
            # print('status 1')

            while MemoryCount < TransferSize:  # /8
                self.device.UpdateWireOuts()
                MemoryCount = self.device.GetWireOutValue(0x26)
                # print('status 2: memory count = %f' % MemoryCount)

            code = self.device.ReadFromBlockPipeOut(0xa0, BlockSize, data_out)
            # print('status 3: memory count = %f' % MemoryCount)

            timestamp[ii] = time.time() - ts0
            print('     timestamp: for frame %i is: %f sec' %
                  (ii, timestamp[ii]))

            if code == TransferSize:
                # #save readout data into bytearray
                print(
                    '     TransferSize match. Data Retrieved: %.1f kB(frames)'
                    % float(int(code) / 1024))
                # with open(args.outputfile + '_img_' + str(i), 'wb') as f:
                #     f.write(data_out)
                #     # print('status 4')
                with open(tsdir + '\\' + sname + '_timestamp', 'wb') as f:
                    f.write(bytes(timestamp))

                with open(sdir + '\\' + sname + '_unparsed_i' + str(ii),
                          'wb') as f:
                    f.write(data_out)
            else:
                print(
                    '     TransferSize doesnt match. Amount of data retrieved from Pipe Out is %d Bytes'
                    % code)
                print('     Do not write file!')
                sys.stderr.write(
                    "     Data was not retrieved correctly. Error code returned is %d Bytes"
                    % code)
                # print('status 5')

                # reset RAM
                # print('     Current memory count is: %d ' % MemoryCount)
                self.device.SetWireInValue(0x00, int(0x00000007))
                self.device.UpdateWireIns()
                self.device.SetWireInValue(0x00, int(fpgaSwitches, 2))
                self.device.UpdateWireIns()

                self.device.UpdateWireOuts()
                MemoryCount = self.device.GetWireOutValue(0x26)
Beispiel #20
0
	def connect(self):
		self.device = ok.okCFrontPanel()
		devCount = 0
		devCount = self.device.GetDeviceCount()
		# Print out list to user for decision.
		self.ctrl.log("Which of the following is the DAC FPGA?")
		for i in range(devCount):
			self.ctrl.log("{0}: Device Model: {1}, Device Serial: {2}".format(i + 1, getDeviceModelFromID(self.device.GetDeviceListModel(i)), self.device.GetDeviceListSerial(i)))
		cont = True
		intChoice = 0
		# Make sure that the response is an integer within the correct range.
		while cont:
			cont = False
			self.ctrl.log("Enter an integer from 1 to {0}:".format(devCount))
			choice = self.ctrl.getUserInput()
			try:
				intChoice = int(choice)
			except ValueError:
				cont = True
				self.ctrl.log("Not an integer.")
			if (intChoice > devCount) or (intChoice < 1):
				self.ctrl.log("Out of Range")
				cont = True
		self.device.OpenBySerial(self.device.GetDeviceListSerial(intChoice - 1))
		self.device.ConfigureFPGA(self.BITFILE_NAME)
		
		if self.device.IsFrontPanelEnabled():
			self.ctrl.log("FrontPanel host interface enabled.")
			self.ctrl.enableGUI()
		else:
			self.ctrl.log("ERROR: FrontPanel host interface not detected.")
			return
		self.ctrl.enableGUI()
		pll22150 = ok.PLL22150()
		# Get the existing settings to modify them
		self.device.GetPLL22150Configuration(pll22150)
		 
		# Modify the PLL settings
		pll22150.SetReference(48.0, False)
		pll22150.SetVCOParameters(400, 48)
		pll22150.SetDiv1(ok.PLL22150.DivSrc_VCO, 400)
		pll22150.SetOutputSource(0, ok.PLL22150.ClkSrc_Div1ByN)
		pll22150.SetOutputEnable(0, True)
		
		# Output Current Settings
		self.ctrl.log("Details for pll:")
		self.ctrl.log("Reference: " + str(pll22150.GetReference()) + "\nVCO Freq: " + str(pll22150.GetVCOFrequency()))
		self.ctrl.log("Div1: " + str(pll22150.GetDiv1Divider()) + "\nSource: " + str(pll22150.GetDiv1Source()))
		self.ctrl.log("Output Freq: " + str(pll22150.GetOutputFrequency(0)) + "\nOutput Source: " + str(pll22150.GetOutputSource(0)))
		self.ctrl.log("VCO P: " + str(pll22150.GetVCOP()) + "\nVCO Q: "+ str(pll22150.GetVCOQ()) + '\n')
		
		# Save new settings to the device
		self.device.SetPLL22150Configuration(pll22150)
		self.device.EnableAsynchronousTransfers(True)
		
		self.setWire0InputBit(8, 0)
		self.setWire1InputBit(0, 0)
		self.updateIns()
		
		thread.start_new_thread(GUI.initAllDacListener, (self.ctrl.gui,))
		thread.start_new_thread(FPGACom.startShift, (self,))
		thread.start_new_thread(FPGACom.startFPChecker, (self,))
		self.setDacState('idle')
Beispiel #21
0
def main():
    dev = ok.okCFrontPanel()
    dev.OpenBySerial("")
    dev.LoadDefaultPLLConfiguration()
    error = dev.ConfigureFPGA("top.bit")
    print(error)
    if dev.IsFrontPanelEnabled() == True:
        print("FrontPanel host interface enabled.")
    else:
        print("FrontPanel host interface not detected.")

    #Open CSV
    fileName = sys.argv[1]
    with open(fileName, newline='') as sineParameters:
        reader = csv.reader(sineParameters)

        next(reader)  #Discard first line (headers)
        firstinputs = next(reader)
        lastTime = sendRowToFPGA(firstinputs, dev)
        dev.ActivateTriggerIn(0x40, 2)
        dev.ActivateTriggerIn(0x40, 0)
        print("Sent one row of inputs in and triggered")

        #Test whether amplitudes got to active section
        dev.UpdateWireOuts()
        activeamp = dev.GetWireOutValue(0x21)
        off = dev.GetWireOutValue(0x22)
        pw = dev.GetWireOutValue(0x23)
        time = dev.GetWireOutValue(0x24)
        print(activeamp)
        print(off)
        print(pw)
        print(time)

        for row in reader:
            print("Sending row {}".format(reader.line_num))

            #Go through one row of values and put in pipes
            newerTime = sendRowToFPGA(row, dev)

            #Wait until last seq done, then read recently completed values and add to array
            readOut(lastTime, dev)
            dev.UpdateWireOuts()
            activeamp = dev.GetWireOutValue(0x21)
            off = dev.GetWireOutValue(0x22)
            pw = dev.GetWireOutValue(0x23)
            time = dev.GetWireOutValue(0x24)
            print(activeamp)
            print(off)
            print(pw)
            print(time)
            lastTime = newerTime

        #When no more rows from csv to send to FPGA, do one last read
        readOut(lastTime, dev)

        #Final plot
        plt.plot(wavelist)
        plt.title("FPGA-Generated Wave")
        plt.xlabel("Cycles @ 110 MHz")
        plt.ylabel("Magnitude")
        plt.savefig("fpgaresult.png")
Beispiel #22
0
            if done != 'y' and done != 'n':
                done = 'y'
    os.close(fd)


if __name__ == "__main__":

    memsize = 4095
    mem = numpy.zeros([256, memsize], dtype=numpy.int)
    # for i in range(256):
    #     for o in range(memsize):
    #         mem[i][o] = 1

    filename = 'finalv3_3.rbf'

    dev = ok.okCFrontPanel()
    devInfo = ok.okTDeviceInfo()

    print "\n--------------------------------------------"
    print "    Welcome to the EHR testing program!"
    print "___|" u"\u203e" "|___|" u"\u203e" "|_|" u"\u203e" "|_|" u"\u203e" "|_|" u"\u203e" "|___|" u"\u203e" "|_|" u"\u203e" "" u"\u203e" "" u"\u203e" "|_|" u"\u203e" "|____"
    print "--------------------------------------------\n"

    accesserror = 0
    #Commented for debug mode
    if dev.OpenBySerial("") != dev.NoError:
        print "Device could not be opened.\nConsider leaving..."
        accesserror += 1
    if (dev.NoError != dev.GetDeviceInfo(devInfo)):
        print("Error: Unable to retrieve device information.")
        accesserror += 1
Beispiel #23
0
 def __init__(self):
     self.xem = ok.okCFrontPanel()
     #self.initializeDevice()
     return
Beispiel #24
0
    def __init__(self,serial = "",filename = "",max_modulus = 100, verbose = False):
        
        #Initialisation resets (->0) the pattern memory up to max_modulus.
        #It is recommended not to reconfigure the FPGA unless it is necessary.
        #The FPGA will only be reconfigured if filename != "".
        #The default design is assumed at "./rbfiles/finalv3_1_top.rbf"
        #It will be used if the FrontPanel interface does not react at the first attempt.
        print "\n---- Initialising the EHR ----\n"
        if max_modulus < 0 or max_modulus >= 4096:
            print "Invalid value for max_modulus. It is set to 4095."
            self.memsize = 4095
        else:
            self.memsize = max_modulus
        self.mem = numpy.zeros([256,self.memsize],dtype=numpy.int)
        self.select = numpy.ones([256,2],dtype=numpy.int)
        
        self.dev = ok.okCFrontPanel()
        self.devInfo = ok.okTDeviceInfo()
        
        if self.dev.OpenBySerial(serial) != self.dev.NoError:
            print "Device could not be opened.\nLeaving..."
            sys.exit(1)
            
        if (self.dev.NoError != self.dev.GetDeviceInfo(self.devInfo)):
            print "Error: Unable to retrieve device information."
            sys.exit(1)

        print("Found Device: " + self.devInfo.productName)
        print("Device ID: %s" % self.devInfo.deviceID)

        if filename != "":
            print "Found configuration file: ",filename
            if self.configureFPGA(filename) == False:
                print "Unable to configure FPGA."
                sys.exit(1)
        else:
            filename = "./rbfiles/finalv3_1_top.rbf"

        #Checking for FrontPanel (USB communication) support
        for i in range(1,7):
            if self.dev.IsFrontPanelEnabled():
                print "FrontPanel is enabled."
                break
            elif i == 6:
                print "Failed to enable FrontPanel. Leaving..."
                sys.exit(1)
            else:
                print "FrontPanel disabled. Reconfiguring...",i
                self.dev.ConfigureFPGA(filename)
        
        if self.reset_pll() == False:
            print "PLL could not be resetted!"
            sys.exit(1)

        #Initialise mem to all 0
        print "Initialising memory...",
        self.mem_data_init = 0
        self.mem_addr_init = 0
        self.dev.SetWireInValue(0x05,self.mem_data_init)
        for bit in range(self.memsize):
            for addr in range(8):
                self.mem_addr_init = int(((addr + (bit*8)) *2) +1)
                self.dev.SetWireInValue(0x04,self.mem_addr_init)
                self.dev.UpdateWireIns()
        self.dev.SetWireInValue(0x04,0)
        self.dev.UpdateWireIns()

        #Initialise select to all 1
        self.sel_data_init = 0xffffffff
        self.sel_addr_init = 0
        self.dev.SetWireInValue(0x03,self.sel_data_init)
        for addr in range(16):
            self.sel_addr_init = (addr*4)+2
            self.dev.SetWireInValue(0x02,self.sel_addr_init)
            self.dev.UpdateWireIns()
        self.dev.SetWireInValue(0x02,0)
        self.dev.UpdateWireIns()

        print "Done"

        #Searching for an external clock
        print "Setting clock to external...",
        if self.set_clock(0) == True:
            print "Done"
        else:
            print "Failed\nThere is no external clock connected!"

        #Resetting the PLL and the phaseshift module
        if self.reset_pll() == False:
            print "PLL could not be resetted!"
            sys.exit(1) 
            
        if verbose:
            print "\n  Initialising wires:"
            print "        pattern_ena = 1"
            print "       trigger data = 0"
            print "     rate parameter = 256"
            print "    all memory data = 0"
            print "          count_mod = %d"%(self.memsize)
            print "\n"
        self.dev.SetWireInValue(0x00,0x00000001)
        self.dev.SetWireInValue(0x01,0x00000100)
        self.dev.SetWireInValue(0x02,0x00000000)
        self.dev.SetWireInValue(0x03,0x00000000)
        self.dev.SetWireInValue(0x04,0x00000000)
        self.dev.SetWireInValue(0x05,0x00000000)
        self.dev.SetWireInValue(0x06,self.memsize)
        self.dev.SetWireInValue(0x07,0x00000000)
        self.dev.UpdateWireIns()
        print "\n"

        self.reset_ran()
        #self.reset_phs()

        return