예제 #1
0
def list_instruments():
    """Get a list of all power supplies currently attached"""
    paramsets = []
    search_string = "ASRL?*"
    rm = ResourceManager()
    raw_spec_list = rm.list_resources(search_string)

    for spec in raw_spec_list:
        try:
            inst = rm.open_resource(spec,
                                    read_termination='\n',
                                    write_termination='\n')
            idn = inst.query("*IDN?")
            manufacturer, model, serial, version = idn.rstrip().split(',', 4)
            if re.match('DP7[0-9]{2}', model):
                paramsets.append(
                    ParamSet(DP700,
                             asrl=spec,
                             manufacturer=manufacturer,
                             serial=serial,
                             model=model,
                             version=version))
        except pyvisa.errors.VisaIOError as vio:
            # Ignore unknown serial devices
            pass

    return paramsets
예제 #2
0
파일: msppwm.py 프로젝트: pigrew/msp399pwm
 def __init__(self, rm: visa.ResourceManager, addr):
     self.addr = addr
     self.inst = rm.open_resource(addr)
     self.inst.baud_rate = 57600
     self.inst.data_bits = 8
     self.inst.query("t?")  # dummy query to clear buffer
     self.inst.query("t0")  # Disable periodic temp report
예제 #3
0
    def __init__(self,
                 signal_interface: SignalInterface,
                 path: str,
                 contacts: Tuple[str, str],
                 v: float = 0.0,
                 i: float = 1e-6,
                 n: int = 100,
                 nplc: int = 1,
                 comment: str = '',
                 gate_voltage: float = 0.0,
                 sd_current_range: float = 0.0,
                 gd_current_range: float = 0.0,
                 symmetric: bool = False) -> None:
        super().__init__(signal_interface, path, contacts)
        self._max_voltage = v
        self._current_limit = i
        self._number_of_points = n
        self._nplc = nplc
        self._comment = comment
        self._gate_voltage = gate_voltage

        resource_man = ResourceManager(self.VISA_LIBRARY)
        resource = resource_man.open_resource(self.GPIB_RESOURCE,
                                              query_delay=self.QUERY_DELAY)

        self._device = Sourcemeter2636A(resource,
                                        sub_device=SMUChannel.channelA)
        self._device.voltage_driven(0, i, nplc, range=sd_current_range)

        self._gate = Sourcemeter2636A(resource, sub_device=SMUChannel.channelB)
        self._gate.voltage_driven(0, i, nplc, range=gd_current_range)

        self._temperature_controller = Model340(self.TEMP_ADDR)

        self._symmetric = symmetric
예제 #4
0
    def __init__(self, location: str, manager: ResourceManager):
        """
        Create a visa connection using loc and manager to the Vidia-Swept laser.

        :param location: the GPIB location of the laser
        :param manager:  the PyVisa resource manager
        """
        self.device = manager.open_resource(location)  # type: GPIBInstrument
    def _init_smus(self):
        rm = ResourceManager('@py')
        dev1 = rm.open_resource(self.GPIB_RESOURCE_2400)
        dev2 = rm.open_resource(self.GPIB_RESOURCE_2636A)
        dev3 = rm.open_resource(self.GPIB_RESOURCE_2602A)

        self._smus = [
            Sourcemeter2400(dev1),
            Sourcemeter2636A(dev2, sub_device=SMUChannel.channelA),
            Sourcemeter2636A(dev2, sub_device=SMUChannel.channelB),
            Sourcemeter2602A(dev3, sub_device=SMUChannel.channelA),
            Sourcemeter2602A(dev3, sub_device=SMUChannel.channelB)
        ]

        for index, smu in enumerate(self._smus):
            sample = self._samples[index]
            smu.voltage_driven(sample['v'],
                               current_limit=sample['i'],
                               nplc=sample['nplc'])
예제 #6
0
파일: oven.py 프로젝트: ehmurray8/KytonUI
    def __init__(self, loc: str, manager: ResourceManager):
        """
        Opens a GPIB connection with the device at the specified location.

        :param loc: the location of the device
        :param manager: the PyVisa Resource Manager
        """
        self.device = manager.open_resource(
            loc, read_termination="\n",
            open_timeout=2500)  # type: GPIBInstrument
예제 #7
0
def test_sanity():

    register_resources(instruments.resources)

    rc = ResourceManager(visa_library="@mock")
    res = rc.open_resource("MOCK0::mock1::INSTR")
    res.write(":INSTR:CHANNEL1:VOLT 2.3")
    reply = res.query(":INSTR:CHANNEL1:VOLT?")

    assert reply == '2.3'
예제 #8
0
    def __init__(self, rm: visa.ResourceManager, addr: str):
        self.dev = rm.open_resource(addr)
        self.dev.clear()

        self.idn = self.dev.query("*IDN?")
        #assert(self.idn == "HP3458A")

        self.dev.write("DISPLAY OFF")
        self.dev.write("CONF:VOLT:DC 10")
        self.dev.write("SENSE:ZERO:AUTO ON")
        self.dev.write("VOLT:DC:NPLC 100")
예제 #9
0
    def __init__(self, signal_interface: SignalInterface,
                 path: str, contacts: Tuple[str, str],
                 v: float = 0.0, i: float = 1e-6,
                 nplc: int = 3, comment: str = '', time_difference: float=0, gpib: str='GPIB0::10::INSTR',
                 temperatures: str = '[2,10,100,300]'):
        super().__init__(signal_interface, path, contacts)
        self._max_voltage = v
        self._current_limit = i
        self._nplc = nplc
        self._comment = comment
        self._time_difference = time_difference
        self._gpib = gpib

        resource_man = ResourceManager('@py')
        resource = resource_man.open_resource(self._gpib)
        resource.timeout = 30000

        self._device = SMUTempSweepIV._get_sourcemeter(resource)
        self._device.voltage_driven(0, i, nplc)
        
        self._temp =  ITC(get_gpib_device(24))
        
        step1 = np.linspace(0, self._max_voltage, 25, endpoint=False)
        step2 = np.linspace(self._max_voltage, -self._max_voltage, 50, endpoint=False)
        step3 = np.linspace(-self._max_voltage, 0, 25)
        self._voltages = np.concatenate((step1, step2, step3))

        try:
            self._temperatures = literal_eval(temperatures)
        except:
            print('ERROR', 'Malformed String for Temperatures')
            self.abort()
            return
            

        if type(self._temperatures) is not list:
            print('ERROR', 'Temperature String is not a List')
            self.abort()
            return
            
        for k in self._temperatures:
            t = type(k)
            
            if t is not int and t is not float:
                print('ERROR', 'Temperature List does not only contain ints or floats')
                self.abort()
                return
                
        self._temperatures = np.array(self._temperatures)
예제 #10
0
    def __init__(self, rm: visa.ResourceManager, addr: str):
        self.dev = rm.open_resource(addr)
        self.dev.read_termination = '\r\n'
        self.dev.write_termination = '\n'
        self.dev.clear()

        self.idn = self.dev.query("ID?")
        assert (self.idn == "HP3458A")
        print("id is {}".format(self.idn))
        self.dev.write("DISP MSG,\"                 \"")

        # Stop auto-trigger
        self.dev.write("TRIG HOLD")
        self.dev.write("NPLC 100")
        self.dev.write("NRDGS 1,LINE")
예제 #11
0
    def __init__(self, signal_interface: SignalInterface,
                 path: str, contacts: Tuple[str, str],
                 v: float = 0.0, i: float = 1e-6, n: int = 100,
                 nplc: int = 1, comment: str = '', range:float=1e-8) -> None:
        super().__init__(signal_interface, path, contacts)
        self._max_voltage = v
        self._current_limit = i
        self._number_of_points = n
        self._nplc = nplc
        self._comment = comment

        resource_man = ResourceManager(self.VISA_LIBRARY)
        resource = resource_man.open_resource(self.GPIB_RESOURCE, query_delay=self.QUERY_DELAY)
        self._device = Sourcemeter2602A(resource)
        self._device.voltage_driven(0, i, nplc, range=range)
예제 #12
0
    def __init__(self, signal_interface: SignalInterface,
                 path: str, contacts: Tuple[str, str],
                 v: float = 0.0, i: float = 1e-6, n: int = 100,
                 nplc: int = 1, comment: str = '', gpib: str = '') -> None:
        super().__init__(signal_interface, path, contacts)
        self._max_voltage = v
        self._current_limit = i
        self._number_of_points = n
        self._nplc = nplc
        self._comment = comment

        resource_man = ResourceManager(self.VISA_LIBRARY)
        resource = resource_man.open_resource(gpib, query_delay=self.QUERY_DELAY)

        try:
            self._device = SMU2Probe._get_sourcemeter(resource)
        except visa.VisaIOError:
            # Should only occur when pyvisa-sim is used:
            self._device = Sourcemeter2400(resource)

        self._device.voltage_driven(0, i, nplc)
예제 #13
0
    def __init__(self,
                 signal_interface: SignalInterface,
                 path: str,
                 contacts: Tuple[str, str],
                 v: float = 0.0,
                 i: float = 1e-6,
                 nplc: int = 3,
                 comment: str = '',
                 time_difference: float = 0,
                 gpib: str = 'GPIB0::10::INSTR'):
        super().__init__(signal_interface, path, contacts)
        self._max_voltage = v
        self._current_limit = i
        self._nplc = nplc
        self._comment = comment
        self._time_difference = time_difference
        self._gpib = gpib

        resource_man = ResourceManager('@py')
        resource = resource_man.open_resource(self._gpib)

        self._device = SMU2ProbeIvt._get_sourcemeter(resource)
        self._device.voltage_driven(0, i, nplc)
예제 #14
0
 def __init__(self, signal_interface: SignalInterface,
              path: str, contacts: Tuple[str, str, str, str],
              comment: str = '', gpib: str='GPIB0::12::INSTR',
              sweep_rate:float = 1.0,
              temperature_end: float = 2,
              nplc: int = 3, voltage:float = 0.1, current_limit: float=1e-6):
                  
     super().__init__(signal_interface, path, contacts)
     self._comment = comment
     self._temp = ITC(get_gpib_device(24))
     self._sweep_rate = sweep_rate
     self._voltage = voltage
     self._current_limit = current_limit
     self._gpib = gpib
         
     if not (0 <= temperature_end <= 299): 
         print("end temperature too high or too low. (0 ... 299)")
         self.abort()
         return  
         
     if not (0 <= sweep_rate <= 2.5): 
         print("you're insane! sweep rate is too high. (0 ... 2.5)")
         self.abort()
         return   
         
     resource_man = ResourceManager('@py')
     resource = resource_man.open_resource(self._gpib)
         
     self._device = SMU2ProbeIvTBlue._get_sourcemeter(resource)
     self._device.voltage_driven(0, current_limit, nplc)
         
     self._temperature_end = temperature_end
     
     self._last_toggle = time()
     
     sleep(1)
예제 #15
0
    def __init__(self, device):
        self.dev = device
        self.dev.write_termination = "\n"
        self.dev.read_termination = "\n"
        self.dev.write('*RST')

    def open(self, route: int):
        """Open the relay on a route."""
        self.dev.write(":ROUTE:OPEN (@1{:02d})".format(route))

    def close(self, route: int):
        """Close the relay on a route."""
        self.dev.write(":ROUTE:CLOSE (@1{:02d})".format(route))


if __name__ == '__main__':
    from visa import ResourceManager
    from time import sleep

    rm = ResourceManager('@py')

    dev = rm.open_resource('GPIB::03::INSTR')

    mux = Multiplexer34970A(dev)

    for i in range(5):
        mux.open(12)
        sleep(1)
        mux.close(12)
        sleep(1)
예제 #16
0
from visa import ResourceManager
from time import sleep

rm = ResourceManager()

ip = "192.168.0.6"
pna = rm.open_resource("TCPIP0::%s::hpib7,16::INSTR" %ip)
pna.read_termination = '\n'
pna.timeout = 8000 #milisecond
pna.write("*RST")

pna.write("FORMat:DATA ASCII,0")

status = pna.query("CALC1:PAR:CAT?")
Catalog = status.replace('"', '').split(',')
print(Catalog)
Mname = Catalog[0]
print("Mname: %s" %Mname)

# sweeping type
pna.write("SENS:SWE:TYPE CW")
sweep_type = pna.query("SENS:SWE:TYPE?")
print("sweep type is %s" %sweep_type)

#sweeping point
pna.write("SENSe:SWEep:POINTs 1001")
point = pna.query("SENSe:SWEep:POINTs?")
print("point = %s" %point)

#sweep frequency
pna.write("SENS:FREQuency:STARt 1e9")
예제 #17
0
 def __init__(self, address):
     rm = ResourceManager()
     self.device = rm.open_resource(address)
     idn = self.query('*IDN?')
     assert '34970A' in idn, 'invalid device identity: %s' % idn
예제 #18
0
class ScopeFinder:

    def __init__(self):
        """
        Constructor
        """

        self.logger = logging.getLogger('scopeout.utilities.ScopeFinder')
        self.logger.info('ScopeFinder Initialized')

        self.resource_manager = ResourceManager()
        self.resources = []
        self.instruments = []
        self.scopes = []
        self.blacklist = set()

        self.refresh()

    def __enter__(self):
        # Entry point for the *with* statement, which allows this object to close properly on program exit.
        return self

    def __exit__(self, type, value, traceback):
        # Exit point for with statement
        pass

    def query(self, inst, command):
        """
        Issues query to instrument and returns response.

        Parameters:
            :inst: the instrument to be queried.
            :command: the command to be issued.

        :Returns: the response of inst as a string.
        """

        return inst.query(command).strip()  # strip newline

    def get_scopes(self):
        """
        Getter for array of connected oscilloscopes.

        :Returns: an array of PyVisa instrument objects representing USB oscilloscopes connected to the computer.
        """

        return self.scopes

    def refresh(self):
        """
        Re-run scope acquisition to update scope array.

        :Returns: the ScopeFinder object, for convenience.
        """

        self.scopes = []
        self.resources = []

        try:
            self.resources = self.resource_manager.list_resources()
        except VisaIOError as e:
            self.resources = []

        if self.resources:
            self.logger.info("%d VISA Resource(s) found", len(self.resources))
            self.instruments = []
            for resource in set(self.resources) - self.blacklist:
                try:
                    inst = self.resource_manager.open_resource(resource)
                    self.instruments.append(inst)
                    self.logger.info('Resource {} converted to instrument'.format(resource))
                except Exception as e:
                    self.logger.error(e)
                    self.blacklist.add(resource)

            for ins in self.instruments:
                try:
                    info = self.query(ins, '*IDN?').split(',')  # Parse identification string
                    if info[1] == 'TDS 2024B':  # TDS 2024B oscilloscope
                        info.append(info.pop().split()[1][3:])  # get our identification string into array format
                        scope = oscilloscopes.TDS2024B(ins, info[1], info[2], info[3])
                        self.scopes.append(scope)
                        self.logger.info("Found %s", str(scope))
                    elif re.match('GDS-1.*A', info[1]):
                        scope = oscilloscopes.GDS1000A(ins, info[1], info[2], info[3])
                        self.scopes.append(scope)
                        self.logger.info("Found %s", str(scope))
                    elif re.match('GDS-2.*A', info[1]):
                        scope = oscilloscopes.GDS2000A(ins, info[1], info[2], info[3])
                        self.scopes.append(scope)
                        self.logger.info("Found %s", str(scope))

                    # Support for other scopes to be implemented here!
                except VisaIOError or IndexError:
                    self.logger.error('{} could not be converted to an oscilloscope'.format(ins))
        return self

    def check_scope(self, scope_index):
        """
        Check if the scope at scopeIndex is still connected.

        Parameters:
            :scopeIndex: the index of the scopes array to check.

        :Returns: True if connected, false otherwise
        """

        try:
            if self.scopes[scope_index].getTriggerStatus():
                return True
            else:
                return False
        except:
            return False
예제 #19
0
                                                   resolution_parameter))
        self.dev.write('SENS:{:s}:NPLC {:f}'.format(method_string,
                                                    integration_time))

    def get_errors(self):
        return self.dev.query('SYST:ERR?')

    def read(self):
        return self.dev.query('READ?')

    @property
    def resistance(self) -> float:
        return float(self.read())


if __name__ == '__main__':
    from visa import ResourceManager
    from time import sleep

    rm = ResourceManager('@py')

    dev = rm.open_resource('GPIB0::9::INSTR')

    mux = Multimeter34401A(dev)

    mux.set_sense(SenseMethod.four_probe_resistance)

    print(mux.get_errors())

    print(mux.read())
예제 #20
0
 def initialise(self):
     rm = ResourceManager()
     self.handle = rm.open_resource(self.address)
예제 #21
0
 def __init__(self, ip):
     rm = ResourceManager()
     self.device = rm.open_resource('TCPIP::%s' % ip)
예제 #22
0
def laser_scan(laser_gpib = "GPIB::19", #1600 GPIB::20 1550 GPIB::4 #1400 GPIB::19
                daq_channel = "dev1/ai1",
                wrange = (1560,1600),
                offsetWL = 0.00,
                sample_rate = 5e3,
                speed = .5, # nm/s (only options are .5 5 40)
                plot_hook = None):
    

    # calculate the output
    total_samples = ((wrange[1] - wrange[0]) /speed * sample_rate )
    wl = np.linspace(wrange[0],wrange[1], total_samples)
    print('Total Samples {:}'.format(total_samples))
    ## Configure task
    voltage_task = daq.InputTask()
    voltage_task.add_analog_voltage_channel(daq_channel,
                                        terminal_config = "rse")
                                        
    voltage_task.configure_sample_clock_timing( sample_rate,
                                            source=b"",
                                            sample_mode=daq.DAQmx_Val_FiniteSamps,
                                            samples_per_channel = int(total_samples))

    ## Set trigger from laser to NIdaq 
    voltage_task.set_digital_trigger(b"PFI0")
    daq.nidaq.DAQmxSetReadReadAllAvailSamp(voltage_task.task_handle, daq.bool32(True))

    ## Connect to laser
    rm = ResourceManager()
    inst =  rm.open_resource(laser_gpib)
    sleep(.1)   
    print('The identification of this instrument is : ' + inst.query("*idn?"))

    ## configure and set to start wl
    inst.write("wav %f nm"%wrange[0])
    inst.write("wav:sweep:start %f nm"%wrange[0])
    inst.write("wav:sweep:STOP %f nm"%wrange[1])
    inst.write("wav:sweep:speed %f nm/s"%(0.5))
    inst.write("TRIGGER:OUTPUT SWStart")
    inst.write("wav:sweep:mode Cont")
    sleep(5)
    

    with voltage_task: # start the task (to avoid lockdown of the nidaq in case of crash)
        ## Start acquisition
        voltage_task.start()
        ## Start scan
        inst.write("WAV:SWEEP:STATE 1")

        # To avoid warnings when the we rea
        warnings.filterwarnings('ignore', 'Read')
    
        ## reading loop. Scan is longer than a second, so we keep
        ## probing to have faster update

        samples_read = 0
        data_buffer = np.zeros(total_samples)
        while samples_read < total_samples:
            b = voltage_task.read()
            if len(b)> 0:
            	data_buffer[samples_read:samples_read+len(b)] = b

            # give an update
            print(len(b), samples_read/total_samples)
            if plot_hook is not None:
            	plot_hook(wl, data_buffer)

            samples_read += len(b)    
            sleep(.3)

    return wl, data_buffer
class DAQ_1DViewer_Tektronix(DAQ_Viewer_base):
    """
        ==================== ========================
        **Attributes**        **Type**
        *data_grabed_signal*  instance of pyqtSignal
        *VISA_rm*             ResourceManager
        *com_ports*           
        *params*              dictionnary list
        *keithley*
        *settings*
        ==================== ========================
    """
    data_grabed_signal = pyqtSignal(list)

    ##checking VISA ressources

    from visa import ResourceManager
    VISA_rm = ResourceManager()
    com_ports = list(VISA_rm.list_resources())

    params = comon_parameters + [
        {
            'title': 'VISA:',
            'name': 'VISA_ressources',
            'type': 'list',
            'values': com_ports
        },
        {
            'title': 'Id:',
            'name': 'id',
            'type': 'text',
            'value': ""
        },
        {
            'title': 'Channels:',
            'name': 'channels',
            'type': 'itemselect',
            'value': dict(all_items=['CH1', 'CH2', 'CH3', 'CH4'],
                          selected=['CH1'])
        },
    ]

    def __init__(self, parent=None, params_state=None):
        super(DAQ_1DViewer_Tektronix, self).__init__(parent, params_state)
        from visa import ResourceManager
        self.VISA_rm = ResourceManager()
        self.controller = None

    def ini_detector(self, controller=None):
        """
            Initialisation procedure of the detector.

            Returns
            -------

                The initialized status.

            See Also
            --------
            daq_utils.ThreadCommand
        """
        self.status.update(
            edict(initialized=False,
                  info="",
                  x_axis=None,
                  y_axis=None,
                  controller=None))
        try:

            if self.settings.child(('controller_status')).value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while this detector is a slave one'
                    )
                else:
                    self.controller = controller
            else:
                self.controller = self.VISA_rm.open_resource(
                    self.settings.child(('VISA_ressources')).value(),
                    read_termination='\n')

            txt = self.controller.query('*IDN?')
            self.settings.child(('id')).setValue(txt)
            Nchannels = self.number_of_channel()
            if Nchannels == 2:
                self.settings.child(('channels')).setValue(
                    dict(all_items=['CH1', 'CH2'], selected=['CH1']))
            else:
                self.settings.child(('channels')).setValue(
                    dict(all_items=['CH1', 'CH2', 'CH3', 'CH4'],
                         selected=['CH1']))

            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status

    def number_of_channel(self):
        """Return the number of available channel on the scope (4 or 2)"""
        if ':CH4:SCA' in self.get_setup_dict().keys():
            return 4
        else:
            return 2

    def load_setup(self):
        l = self.controller.query('SET?')
        dico = dict(
            [e.split(' ') for e in l.split(';')[1:] if len(e.split(' ')) == 2])
        self.dico = dico

    def get_setup_dict(self, force_load=False):
        """Return the dictionnary of the setup

        By default, the method does not load the setup from the instrument
        unless it has not been loaded before or force_load is set to true.
        """
        if not hasattr(self, 'dico') or force_load:
            self.load_setup()
        return self.dico

    def commit_settings(self, param):
        """
            Activate the parameters changes in the hardware.

            =============== ================================= ============================
            **Parameters**   **Type**                         **Description**
            *param*         instance of pyqtgraph.parameter   The parameter to be checked.
            =============== ================================= ============================

            See Also
            --------
            daq_utils.ThreadCommand
        """
        try:
            pass

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))

    def close(self):
        """
            close the current instance.
        """
        self.controller._inst.close(
        )  #the close method has not been written in tektronix object

    def grab_data(self, Naverage=1, **kwargs):
        """
            | Start new acquisition.
            | grab the current values with keithley profile procedure.
            | Send the data_grabed_signal once done.

            =============== ======== ===============================================
            **Parameters**  **Type**  **Description**
            *Naverage*      int       Number of values to average
            =============== ======== ===============================================
        """
        data_tot = []
        x_axis = None
        for ind, channel in enumerate(
                self.settings.child(('channels')).value()['selected']):
            if ind == 0:
                x_axis, data_tmp = self.read_channel_data(channel,
                                                          x_axis_out=True)
            else:
                data_tmp = self.read_channel_data(channel, x_axis_out=False)
            data_tot.append(data_tmp)

        self.data_grabed_signal.emit([
            DataFromPlugins(name='Tektronix',
                            data=data_tot,
                            dim='Data1D',
                            x_axis=Axis(data=x_axis, label='Time', units='s'))
        ])

    def get_out_waveform_horizontal_sampling_interval(self):
        return float(self.controller.query('WFMO:XIN?'))

    def get_out_waveform_horizontal_zero(self):
        return float(self.controller.query('WFMO:XZERO?'))

    def get_out_waveform_vertical_scale_factor(self):
        return float(self.controller.query('WFMO:YMUlt?'))

    def get_out_waveform_vertical_position(self):
        return float(self.controller.query('WFMO:YOFf?'))

    def get_data_start(self):
        return int(self.controller.query('DATA:START?'))

    def get_horizontal_record_length(self):
        return int(self.controller.query("horizontal:recordlength?"))

    def get_data_stop(self):
        return int(self.controller.query('DATA:STOP?'))

    def set_data_source(self, name):
        self.controller.write('DAT:SOUR ' + str(name))

    def read_channel_data(self, channel, x_axis_out=False):
        self.controller.write("DATA:ENCDG ASCII")
        self.controller.write("DATA:WIDTH 2")
        if channel is not None:
            self.set_data_source(channel)
        self.offset = self.get_out_waveform_vertical_position()
        self.scale = self.get_out_waveform_vertical_scale_factor()
        if x_axis_out:
            self.data_start = self.get_data_start()
            self.data_stop = self.get_data_stop()
            self.x_0 = self.get_out_waveform_horizontal_zero()
            self.delta_x = self.get_out_waveform_horizontal_sampling_interval()

            X_axis = self.x_0 + np.arange(
                0, self.get_horizontal_record_length()) * self.delta_x

        res = np.array(self.controller.query_ascii_values('CURVE?'))
        #res = np.frombuffer(buffer, dtype=np.dtype('int16').newbyteorder('<'),
        #                    offset=0)

        # The output of CURVE? is scaled to the display of the scope
        # The following converts the data to the right scale
        Y_axis = (res - self.offset) * self.scale

        if x_axis_out:
            return X_axis, Y_axis
        else:
            return Y_axis

    def stop(self):
        """
            not implemented?
        """
        return ""
예제 #24
0
 def __init__(self, visa_call_name, rm: ResourceManager):
     self.dmm = rm.open_resource(visa_call_name)
class DAQ_0DViewer_Keithley_Pico(DAQ_Viewer_base):
    """
        ==================== ========================
        **Attributes**        **Type**
        *data_grabed_signal*  instance of pyqtSignal
        *VISA_rm*             ResourceManager
        *com_ports*           
        *params*              dictionnary list
        *keithley*
        *settings*
        ==================== ========================
    """
    data_grabed_signal = pyqtSignal(list)

    ##checking VISA ressources

    from visa import ResourceManager
    VISA_rm = ResourceManager()
    com_ports = list(VISA_rm.list_resources())
    #    import serial.tools.list_ports;
    #    com_ports=[comport.device for comport in serial.tools.list_ports.comports()]

    params = comon_parameters + [
        {
            'title': 'VISA:',
            'name': 'VISA_ressources',
            'type': 'list',
            'values': com_ports
        },
        {
            'title': 'Keithley Type:',
            'name': 'keithley_type',
            'type': 'list',
            'values': DAQ_0DViewer_Keithley_Pico_type.names()
        },
        {
            'title': 'Id:',
            'name': 'id',
            'type': 'text',
            'value': ""
        },
        {
            'title': 'Timeout (ms):',
            'name': 'timeout',
            'type': 'int',
            'value': 10000,
            'default': 10000,
            'min': 2000
        },
        {
            'title':
            'Configuration:',
            'name':
            'config',
            'type':
            'group',
            'children': [
                {
                    'title': 'Meas. type:',
                    'name': 'meas_type',
                    'type': 'list',
                    'value': 'CURR',
                    'default': 'CURR',
                    'values': ['CURR', 'VOLT', 'RES', 'CHAR']
                },
            ]
        },
    ]

    def __init__(self, parent=None, params_state=None):
        super(DAQ_0DViewer_Keithley_Pico, self).__init__(parent, params_state)
        from visa import ResourceManager
        self.VISA_rm = ResourceManager()
        self.controller = None

    def ini_detector(self, controller=None):
        """
            Initialisation procedure of the detector.

            Returns
            -------

                The initialized status.

            See Also
            --------
            daq_utils.ThreadCommand
        """
        self.status.update(
            edict(initialized=False,
                  info="",
                  x_axis=None,
                  y_axis=None,
                  controller=None))
        try:

            if self.settings.child(('controller_status')).value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while this detector is a slave one'
                    )
                else:
                    self.controller = controller
            else:
                self.controller = self.VISA_rm.open_resource(
                    self.settings.child(('VISA_ressources')).value(),
                    read_termination='\r')

            self.controller.timeout = self.settings.child(('timeout')).value()

            self.controller.write("*rst; status:preset; *cls;")
            txt = self.controller.query('*IDN?')
            self.settings.child(('id')).setValue(txt)
            self.controller.write(
                'CONF:' + self.settings.child('config', 'meas_type').value())
            self.controller.write(':FORM:ELEM READ;DATA ASC;')
            self.controller.write('ARM:SOUR IMM;')
            self.controller.write('ARM:COUNt 1;')
            self.controller.write('TRIG:SOUR IMM;')
            #%%
            data = self.controller.query_ascii_values('READ?')

            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status

    def commit_settings(self, param):
        """
            Activate the parameters changes in the hardware.

            =============== ================================= ============================
            **Parameters**   **Type**                         **Description**
            *param*         instance of pyqtgraph.parameter   The parameter to be checked.
            =============== ================================= ============================

            See Also
            --------
            daq_utils.ThreadCommand
        """
        try:
            if param.name() == 'timeout':
                self.controller.timeout = self.settings.child(
                    ('timeout')).value()
            elif param.name() == 'meas_type':
                self.controller.write('CONF:' + param.value())

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))

    def close(self):
        """
            close the current instance of Keithley viewer.
        """
        self.controller.close()

    def grab_data(self, Naverage=1, **kwargs):
        """
            | Start new acquisition.
            | grab the current values with keithley profile procedure.
            | Send the data_grabed_signal once done.

            =============== ======== ===============================================
            **Parameters**  **Type**  **Description**
            *Naverage*      int       Number of values to average
            =============== ======== ===============================================
        """
        data_tot = []
        self.controller.write('ARM:SOUR IMM;')
        self.controller.write('ARM:COUNt 1;')
        self.controller.write('TRIG:SOUR IMM;')
        self.controller.write('TRIG:COUN {:};'.format(Naverage))
        data_tot = self.controller.query_ascii_values('READ?')
        #for ind in range(Naverage):
        #    data_tot.append(self.controller.query_ascii_values('READ?')[0])
        data_tot = [np.array([np.mean(np.array(data_tot))])]
        self.data_grabed_signal.emit(
            [DataFromPlugins(name='Keithley', data=data_tot, dim='Data0D')])

    def stop(self):
        """
            not implemented?
        """
        return ""