Ejemplo n.º 1
0
def count(high_time, low_time, samples):
    global Reader, data

    print('Configure internal connections..')
    system = System.local()
    system.connect_terms('/Dev1/PFI32', '/Dev1/RTSI0')
    with Task('ct1_task') as ct1_task, Task('timer') as timer_task:
        data = np.zeros(samples)
        # configure counter channel and task
        ct1 = ct1_task.ci_channels.add_ci_pulse_width_chan(
            'Dev1/ctr2', 'counter', min_val=2, max_val=100000000,
            units=TimeUnits.TICKS)
        ct1_task.timing.cfg_implicit_timing(samps_per_chan=samples)
        ct1.ci_ctr_timebase_src = '/Dev1/PFI31'
        ct1.ci_pulse_width_term = '/Dev1/RTSI0'
        Reader = CounterReader(ct1_task.in_stream)

        ct1_task.register_every_n_samples_acquired_into_buffer_event(
        1, sample_readies)

        ct1_task.start()

        timer_task.co_channels.add_co_pulse_chan_time(
            'Dev1/ctr1', high_time=high_time, low_time=low_time)
        timer_task.timing.cfg_implicit_timing(
            sample_mode=AcquisitionType.FINITE, samps_per_chan=samples)
        timer_task.start()

        while not timer_task.is_task_done():
             time.sleep(0.001)
        print(data)
        print(len(data))
Ejemplo n.º 2
0
    def __init__(self,
                 channel,
                 channel_name,
                 gate_src,
                 timebase_src,
                 edge=Edge.RISING):
        self._thread = None
        self._stop = False
        self._channel = channel
        self._data = np.zeros(0)
        self.sample_readies = 0
        self.enabled = True
        # Create the task
        self._task = Task('task' + channel_name)

        # Add pulse width channel
        self._counter = self._task.ci_channels.add_ci_pulse_width_chan(
            channel, channel_name, units=TimeUnits.TICKS, starting_edge=edge)

        # Configure timing and data transfer mechanims
        self._task.timing.samp_timing_type = SampleTimingType.IMPLICIT
        self._counter.ci_data_xfer_mech = \
            DataTransferActiveTransferMode.INTERRUPT

        # Configure the source and the gate
        self._counter.ci_ctr_timebase_src = timebase_src
        self._counter.ci_pulse_width_term = gate_src

        # Configure reader.
        self._task.in_stream.read_all_avail_samp = True
        self._reader = CounterReader(self._task.in_stream)
Ejemplo n.º 3
0
class PulseGenerator:
    def __init__(self, channel, start_src=None):
        self._task = None
        self._channel = channel

        # TODO implement external start

    def __del__(self):
        if self._task is not None:
            self._task.close()

    def start(self, samples, high_time, low_time, initial_delay=0):
        if self._task is not None:
            self._task.close()
        self._task = Task('timer')
        self._timer = self._task.co_channels.add_co_pulse_chan_time(
            self._channel,
            high_time=high_time,
            low_time=low_time,
            initial_delay=initial_delay)
        self._task.timing.samp_quant_samp_per_chan = samples
        self._task.timing.samp_timing_type = SampleTimingType.IMPLICIT
        self._task.start()

    def stop(self):
        self._task.stop()

    @property
    def done(self):
        return self._task.is_task_done()
Ejemplo n.º 4
0
 def __init__(self):
     """Constructor method
     """
     super(DAQmxSystem, self).__init__()
     self.task = Task()
     self.reading = False
     self.stop_lock = asyncio.Lock()
     self.read_lock = asyncio.Lock()
Ejemplo n.º 5
0
 def test_task_duplicate(self):
     with Task("task") as t:
         with pytest.raises(DaqError) as dupe_exception:
             u = Task("task")
             # u is now partially constructed, and deleting it should be safe. This previously
             # raised an exception which was uncatchable. pytest should fail with that, but it
             # doesn't seem to be working. Regardless it will print a warning that contributors
             # should see if it regresses.
             del(u)
         assert dupe_exception.value.error_code == DAQmxErrors.DUPLICATE_TASK
Ejemplo n.º 6
0
 def __init__(self):
     Task.__init__(self)
     self.data = zeros(1000)
     self.a = []
     self.CreateAIVoltageChan("Dev1/ai0", "", DAQmx_Val_RSE, -10.0, 10.0,
                              DAQmx_Val_Volts, None)
     self.CfgSampClkTiming("", 10000.0, DAQmx_Val_Rising,
                           DAQmx_Val_ContSamps, 1000)
     self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,
                                         1000, 0)
     self.AutoRegisterDoneEvent(0)
Ejemplo n.º 7
0
 def start(self, samples, high_time, low_time, initial_delay=0):
     if self._task is not None:
         self._task.close()
     self._task = Task('timer')
     self._timer = self._task.co_channels.add_co_pulse_chan_time(
         self._channel,
         high_time=high_time,
         low_time=low_time,
         initial_delay=initial_delay)
     self._task.timing.samp_quant_samp_per_chan = samples
     self._task.timing.samp_timing_type = SampleTimingType.IMPLICIT
     self._task.start()
Ejemplo n.º 8
0
class PulseCounter:
    """
    Class to implement a pulse counter
    """
    def __init__(self,
                 channel,
                 channel_name,
                 gate_src,
                 timebase_src,
                 edge=Edge.RISING):
        self._data = None
        self.sample_readies = 0

        self._channel = channel
        self._task = Task('task' + channel_name)
        self._counter = self._task.ci_channels.add_ci_pulse_width_chan(
            channel, channel_name, units=TimeUnits.TICKS, starting_edge=edge)
        self._counter.ci_ctr_timebase_src = timebase_src
        self._counter.ci_pulse_width_term = gate_src
        self._task.in_stream.read_all_avail_samp = True
        self._reader = CounterReader(self._task.in_stream)
        self._thread = None
        self._stop = False

    def __del__(self):
        self._task.close()

    def start(self, samples):
        self._data = np.zeros(samples)
        self._task.stop()
        self._data = np.zeros(samples)
        self._task.timing.samp_quant_samp_per_chan = samples
        self._task.timing.samp_timing_type = SampleTimingType.IMPLICIT
        self._counter.ci_data_xfer_mech = \
            DataTransferActiveTransferMode.INTERRUPT
        self._thread = threading.Thread(target=self._read, args=[samples])
        self._task.start()
        self._stop = False
        self._thread.start()

    @property
    def done(self):
        return self._task.is_task_done()

    def stop(self):
        self._stop = True
        self._task.stop()

    def _read(self, samples):
        i = 0
        while not self._stop and samples != 0:
            self._data[i] = self._reader.read_one_sample_double(timeout=-1)
            i += 1
            samples -= 1

    @property
    def data(self):
        return self._data
Ejemplo n.º 9
0
    def __init__(self, channel, channel_name):
        self._thread = None
        self._stop = False
        self._channel = channel
        self._data = np.zeros(0)
        self.sample_readies = 0
        self.enabled = True

        # Create the task
        self._task = Task('task' + channel_name)

        # Configure reader.
        self._task.in_stream.read_all_avail_samp = True
        self._reader = CounterReader(self._task.in_stream)
Ejemplo n.º 10
0
def reset_devices(task: nidaqmx.Task):
    """
    Reset all devices, clear the task and returns a new empty task with the same name.
    Args:
        task: object to reset
    Return:
        Object after reset
    """
    devices = task.devices
    task_name = task.name
    task.close()
    for device in devices:
        device.reset_device()
    return nidaqmx.Task(task_name)
Ejemplo n.º 11
0
    def __init__(self,
                 channel,
                 channel_name,
                 gate_src,
                 timebase_src,
                 edge=Edge.RISING):
        self._data = None
        self.sample_readies = 0

        self._channel = channel
        self._task = Task('task' + channel_name)
        self._counter = self._task.ci_channels.add_ci_pulse_width_chan(
            channel, channel_name, units=TimeUnits.TICKS, starting_edge=edge)
        self._counter.ci_ctr_timebase_src = timebase_src
        self._counter.ci_pulse_width_term = gate_src
        self._task.in_stream.read_all_avail_samp = True
        self._reader = CounterReader(self._task.in_stream)
        self._thread = None
        self._stop = False
Ejemplo n.º 12
0
def read_from_daq(counterStr: str, timeoutSecFloat: float) -> float:
    """
    Read from the DAQ with a timeout.
    """
    with Task() as task:
        # https://nidaqmx-python.readthedocs.io/en/latest/ci_channel_collection.html#nidaqmx._task_modules.ci_channel_collection.CIChannelCollection.add_ci_two_edge_sep_chan
        task.ci_channels.add_ci_two_edge_sep_chan(counter=counterStr,
                                                  first_edge=Edge.RISING,
                                                  max_val=1.0,
                                                  min_val=0.0000001,
                                                  second_edge=Edge.FALLING,
                                                  units=TimeUnits.SECONDS)
        return task.read(timeout=timeoutSecFloat)
Ejemplo n.º 13
0
    def run_scanning(self):
        while not self.stop_event.is_set():
            toggle_shutter = False
            if (self.new_parameters.scanning_state == ScanningState.PAUSED
                    and self.scanning_parameters.scanning_state !=
                    ScanningState.PAUSED
                ) or (
                    self.new_parameters.scanning_state != ScanningState.PAUSED
                    and self.scanning_parameters.scanning_state
                    == ScanningState.PAUSED):
                toggle_shutter = True

            self.scanning_parameters = self.new_parameters
            self.compute_scan_parameters()
            with Task() as write_task, Task() as read_task, Task(
            ) as shutter_task:
                self.setup_tasks(read_task, write_task, shutter_task)
                if self.scanning_parameters.reset_shutter or toggle_shutter:
                    self.toggle_shutter(shutter_task)
                if self.scanning_parameters.scanning_state == ScanningState.PAUSED:
                    self.pause_loop()
                else:
                    self.scan_loop(read_task, write_task)
Ejemplo n.º 14
0
class BaseChannel:
    """
    Base class to implement a channel
    """
    def __init__(self, channel, channel_name):
        self._thread = None
        self._stop = False
        self._channel = channel
        self._data = np.zeros(0)
        self.sample_readies = 0
        self.enabled = True

        # Create the task
        self._task = Task('task' + channel_name)

        # Configure reader.
        self._task.in_stream.read_all_avail_samp = True
        self._reader = CounterReader(self._task.in_stream)

        # Configure timing

    def __del__(self):
        self._task.close()

    def start(self, samples):
        self._task.stop()
        self._data = np.zeros(samples)
        self.sample_readies = 0
        if not self.enabled:
            return
        if samples == 1:
            self._task.timing.samp_quant_samp_per_chan = 2
        else:
            self._task.timing.samp_quant_samp_per_chan = samples
        self._stop = False
        self._thread = threading.Thread(target=self._read, args=[samples])
        self._task.start()
        self._thread.start()

    @property
    def data(self):
        return self._data[:self.sample_readies]

    @property
    def done(self):
        return self._task.is_task_done()

    def stop(self):
        self._stop = True
        self._task.stop()

    def _read(self, samples):
        i = 0
        while not self._stop and samples != 0:
            self._data[i] = self._reader.read_one_sample_double(timeout=-1)
            i += 1
            samples -= 1
            self.sample_readies += 1

        self._task.stop()
from csv import reader
from math import sqrt
from nidaqmx import Task
from nidaqmx.constants import LineGrouping
from pyvisa import ResourceManager
from sklearn.linear_model import LogisticRegression
from time import sleep, time

input(
    "Ensure that all of the instruments are powered on and configured properly."
)
input("Ensure that the DUT is seated firmly in the test socket.")

# Scan the device using the S11 method.
with Task() as task:
    task.ao_channels.add_ao_voltage_chan("myDAQ1/ao0")
    task.write([3.3], auto_start=True)

sample = []

for permutation in range(256):
    print("Performing S11 measurement on permutation " + str(permutation + 1) +
          " of 256.")

    # Add an empty list to the sample list.
    sample.append([])

    # Write to the SIPO registers on the PCB to set the relays.
    with Task() as task:
        task.do_channels.add_do_chan(
Ejemplo n.º 16
0
    def run(self):
        self.digital_out_data = np.zeros_like(self.tout, dtype=np.uint32)
        self.digital_out_data = set_bit(self.digital_out_data, self.params['DAQ', 'Output', 'Inhibit line'],
                                        self.inhibit)
        self.digital_out_data = set_bit(self.digital_out_data, self.params['DAQ', 'Output', 'Enable line'],
                                        self.enable)
        self.digital_out_data = set_bit(self.digital_out_data, self.params['DAQ', 'Output', 'LED line'],
                                        self.led)

        if self.params['DAQ', 'Reference trigger'].lower() == 'none':
            trig = None
            pretrigdur = 0
        else:
            trig = self.params['DAQ', 'Reference trigger'].lower()
            pretrigdur = self.params['DAQ', 'Pretrigger duration']

        try:
            with Task() as counter_out, \
                    Task() as digital_out, \
                    Task() as analog_in, \
                    Task() as digital_in:
                # digital output
                digital_out.do_channels.add_do_chan(self.params['DAQ', 'Output', 'Digital port'],
                                                    line_grouping=daq.LineGrouping.CHAN_FOR_ALL_LINES)
                digital_out.timing.cfg_samp_clk_timing(self.params['Motor', 'Pulse frequency'],
                                                       sample_mode=daq.AcquisitionType.FINITE,
                                                       samps_per_chan=len(self.digital_out_data))
                if trig is None:
                    digital_out.triggers.start_trigger.cfg_dig_edge_start_trig('ai/StartTrigger',
                                                                               trigger_edge=daq.Edge.RISING)
                else:
                    digital_out.triggers.start_trigger.cfg_dig_edge_start_trig(trig,
                                                                               trigger_edge=daq.Edge.RISING)
                # order is inhibit then enable
                # digital_out.write([False, True], auto_start=True)
                digital_writer = DigitalSingleChannelWriter(digital_out.out_stream)
                digital_writer.write_many_sample_port_uint32(self.digital_out_data)

                totaldur = self.duration + pretrigdur
                # analog input
                n_in_samples = int(totaldur * self.params['DAQ', 'Input', 'Sampling frequency'])
                n_in_pre_samples = int(pretrigdur * self.params['DAQ', 'Input', 'Sampling frequency'])

                aichans = [self.params['DAQ','Input', c] for c in ['SG0', 'SG1', 'SG2', 'SG3', 'SG4', 'SG5']]
                for aichan1 in aichans:
                    analog_in.ai_channels.add_ai_voltage_chan(aichan1)
                analog_in.timing.cfg_samp_clk_timing(self.params['DAQ', 'Input', 'Sampling frequency'],
                                                     sample_mode=daq.AcquisitionType.FINITE,
                                                     samps_per_chan=n_in_samples)
                if trig is not None:
                    analog_in.triggers.reference_trigger.cfg_dig_edge_ref_trig(self.params['DAQ', 'Reference trigger'],
                                                                               n_in_pre_samples,
                                                                               trigger_edge=daq.Edge.RISING)
                # analog_in.triggers.start_trigger.cfg_dig_edge_start_trig(self.params['DAQ', 'Start trigger'],
                #                                                          trigger_edge=daq.Edge.RISING)

                reader = AnalogMultiChannelReader(analog_in.in_stream)
                self.aidata = np.zeros((6, n_in_samples), dtype=np.float64)

                # digital input
                n_in_dig_samples = int(totaldur * self.params['DAQ', 'Input', 'Digital sampling frequency'])
                n_in_dig_pre_samples = int(pretrigdur * self.params['DAQ', 'Input', 'Digital sampling frequency'])

                digital_in.di_channels.add_di_chan(self.params['DAQ', 'Input', 'Digital input port'], '',
                                                   line_grouping=daq.LineGrouping.CHAN_FOR_ALL_LINES)
                digital_in.timing.cfg_samp_clk_timing(self.params['DAQ', 'Input', 'Digital sampling frequency'],
                                                      sample_mode=daq.AcquisitionType.FINITE,
                                                      samps_per_chan=n_in_dig_samples)
                if trig is not None:
                    digital_in.triggers.reference_trigger.cfg_dig_edge_ref_trig(self.params['DAQ', 'Reference trigger'],
                                                                                n_in_dig_pre_samples,
                                                                                trigger_edge=daq.Edge.RISING)
                else:
                    digital_in.triggers.start_trigger.cfg_dig_edge_start_trig('ai/StartTrigger',
                                                                              trigger_edge=daq.Edge.RISING)
                # digital_in.triggers.start_trigger.cfg_dig_edge_start_trig(self.params['DAQ', 'Start trigger'],
                #                                                           trigger_edge=daq.Edge.RISING)
                digital_reader = DigitalSingleChannelReader(digital_in.in_stream)
                self.didata = np.zeros(n_in_dig_samples, dtype=np.uint32)

                # counter output
                if self.params['Movement', 'Position amplitude'] != 0:
                    counter_out.co_channels.add_co_pulse_chan_freq(self.params['DAQ', 'Output', 'Counter name'],
                                                                   units=daq.FrequencyUnits.HZ,
                                                                   idle_state=daq.Level.LOW, initial_delay=0.0,
                                                                   freq=self.params['Motor', 'Pulse frequency'],
                                                                   duty_cycle=0.5)
                    counter_out.timing.cfg_implicit_timing(sample_mode=daq.AcquisitionType.FINITE,
                                                           samps_per_chan=len(self.duty))
                    if trig is not None:
                        counter_out.triggers.start_trigger.cfg_dig_edge_start_trig(trig,
                                                                                   trigger_edge=daq.Edge.RISING)
                    else:
                        counter_out.triggers.start_trigger.cfg_dig_edge_start_trig('ai/StartTrigger',
                                                                                   trigger_edge=daq.Edge.RISING)

                    counter_writer = CounterWriter(counter_out.out_stream)

                    counter_writer.write_many_sample_pulse_frequency(self.freq, self.duty)

                    iscounter = True
                else:
                    iscounter = False

                digital_out.start()
                if iscounter:
                    counter_out.start()
                digital_in.start()

                analog_in.start()

                analog_in.wait_until_done(60)
                self.endTime = datetime.now()

                reader.read_many_sample(self.aidata)
                digital_reader.read_many_sample_port_uint32(self.didata)
        except DaqError as daqerr:
            QtWidgets.QMessageBox.critical(None, 'Error', str(daqerr))
        finally:
            pass
            # digital_out.write([True, False], auto_start=True)

        self.tin = np.arange(0, n_in_samples) / self.params['DAQ', 'Input', 'Sampling frequency']
        self.tin -= self.params['Movement', 'Wait before and after'] + pretrigdur

        self.tdig = np.arange(0, n_in_dig_samples) / self.params['DAQ', 'Input', 'Digital sampling frequency']
        self.tdig -= self.params['Movement', 'Wait before and after'] + pretrigdur

        self.forces = np.dot(self.aidata.T, self.calibration).T
        self.pwm = np.bitwise_and(self.didata, 2**self.params['DAQ', 'Input', 'PWM return line']) > 0
        self.V3Vpulse = np.bitwise_and(self.didata, 2**self.params['DAQ', 'Input', 'V3V pulse line']) > 0
        self.V3Vpulse2 = np.bitwise_and(self.didata, 2**self.params['DAQ', 'Input', 'V3V pulse2']) > 0
        self.V3Vpulse3 = np.bitwise_and(self.didata, 2**self.params['DAQ', 'Input', 'V3V pulse3']) > 0
Ejemplo n.º 17
0
class DAQmxSystem(AcquisitionCard):
    def __init__(self):
        super(DAQmxSystem, self).__init__()
        self.task = Task()
        self.reading = False
        self.stop_lock = asyncio.Lock()
        self.read_lock = asyncio.Lock()

    @property
    def samp_clk_max_rate(self):
        return self.task.timing.samp_clk_max_rate

    def possible_trigger_channels(self):
        return [chan.name for chan in self.channels]

    def close(self):
        if self.task:
            self.channels = []
            self.task.close()
            self.task = None

    def add_channel(self, channel_name, terminal_config, voltage_range):
        tc = ConcreteTerminalConfig[terminal_config]
        ai_chan = self.task.ai_channels.add_ai_voltage_chan(
            channel_name,
            terminal_config=tc,
            min_val=-voltage_range,
            max_val=voltage_range,
        )
        self.channels.append(ai_chan)
        self.actual_ranges.append(ai_chan.ai_max)

    def configure_clock(self, sample_rate, samples_per_chan):
        self.task.timing.cfg_samp_clk_timing(sample_rate,
                                             samps_per_chan=samples_per_chan)
        self.sample_rate = sample_rate
        self.samples_per_chan = samples_per_chan

    def configure_trigger(
        self,
        trigger_source=None,
        trigger_level=0,
        trigger_config=TriggerConfig.EdgeRising,
    ):

        st = self.task.triggers.start_trigger
        if trigger_source is None:
            print("disable_start_trig")
            st.disable_start_trig()
        else:
            if trigger_config != TriggerConfig.EdgeRising:
                raise NotImplementedError()  # TODO
            print(
                f"cfg_anlg_edge_start_trig({trigger_source:}, {trigger_level:})"
            )
            st.cfg_anlg_edge_start_trig(trigger_source,
                                        trigger_level=trigger_level)

    def start(self):
        self.task.start()
        self.running = True

    async def stop(self):
        async with self.stop_lock:
            if self.running:
                self.running = False
                while self.reading:
                    await asyncio.sleep(1.0)
                self.task.stop()

    async def read(self, tmo=None):
        async with self.read_lock:
            self.reading = True
            done = False
            start = time.monotonic()
            while self.running:
                try:
                    await self.loop.run_in_executor(None,
                                                    self.task.wait_until_done,
                                                    1.0)
                except DaqError:
                    if tmo and time.monotonic() - start > tmo:
                        raise TimeoutException()
                    else:
                        continue
                done = True
                break
            if done and self.running:
                data = await self.loop.run_in_executor(None, self.task.read,
                                                       READ_ALL_AVAILABLE)
                self.last_read = time.monotonic()
                data = np.array(data)
            else:
                data = None
            self.reading = False
            return data
Ejemplo n.º 18
0
 def __init__(self):
     super(DAQmxSystem, self).__init__()
     self.task = Task()
     self.reading = False
     self.stop_lock = asyncio.Lock()
     self.read_lock = asyncio.Lock()
Ejemplo n.º 19
0
class DAQmxSystem(AcquisitionCard):
    """This class is the concrete implementation for NI DAQmx board using
    the :mod:`nidaqmx` module.
    """
    def __init__(self):
        """Constructor method
        """
        super(DAQmxSystem, self).__init__()
        self.task = Task()
        self.reading = False
        self.stop_lock = asyncio.Lock()
        self.read_lock = asyncio.Lock()

    @property
    def samp_clk_max_rate(self):
        """Maximum sample clock rate
        """
        return self.task.timing.samp_clk_max_rate

    def possible_trigger_channels(self):
        """This method returns the list of channels that can be used as trigger.
        """
        return [chan.name for chan in self.channels]

    def close(self):
        """This method closes the active task, if there is one.
        """
        if self.task:
            self.channels = []
            self.task.close()
            self.task = None

    def add_channel(self, channel_name, terminal_config, voltage_range):
        """Concrete implementation of :meth:`pymanip.aiodaq.AcquisitionCard.add_channel`.

        .. todo::
            Actually check the type for terminal_config.

        """
        tc = ConcreteTerminalConfig[terminal_config]
        ai_chan = self.task.ai_channels.add_ai_voltage_chan(
            channel_name,
            terminal_config=tc,
            min_val=-voltage_range,
            max_val=voltage_range,
        )
        self.channels.append(ai_chan)
        self.actual_ranges.append(ai_chan.ai_max)

    def configure_clock(self, sample_rate, samples_per_chan):
        """Concrete implementation of :meth:`pymanip.aiodaq.AcquisitionCard.configure_clock`
        """
        self.task.timing.cfg_samp_clk_timing(sample_rate,
                                             samps_per_chan=samples_per_chan)
        self.sample_rate = sample_rate
        self.samples_per_chan = samples_per_chan

    def configure_trigger(
        self,
        trigger_source=None,
        trigger_level=0,
        trigger_config=TriggerConfig.EdgeRising,
    ):
        """Concrete implementation of :meth:`pymanip.aiodaq.AcquisitionCard.configure_trigger`

        .. todo::
           implement trigger_config other than the defaults value

        """

        st = self.task.triggers.start_trigger
        if trigger_source is None:
            print("disable_start_trig")
            st.disable_start_trig()
        else:
            if trigger_config != TriggerConfig.EdgeRising:
                raise NotImplementedError()  # TODO
            print(
                f"cfg_anlg_edge_start_trig({trigger_source:}, {trigger_level:})"
            )
            st.cfg_anlg_edge_start_trig(trigger_source,
                                        trigger_level=trigger_level)

    def start(self):
        """This method starts the task.
        """
        self.task.start()
        self.running = True

    async def stop(self):
        """This asynchronous method aborts the current task.
        """
        async with self.stop_lock:
            if self.running:
                self.running = False
                while self.reading:
                    await asyncio.sleep(1.0)
                self.task.stop()

    async def read(self, tmo=None):
        """This asynchronous method reads data from the task.
        """
        async with self.read_lock:
            self.reading = True
            done = False
            start = time.monotonic()
            while self.running:
                try:
                    await self.loop.run_in_executor(None,
                                                    self.task.wait_until_done,
                                                    1.0)
                except DaqError:
                    if tmo and time.monotonic() - start > tmo:
                        raise TimeoutException()
                    else:
                        continue
                done = True
                break
            if done and self.running:
                data = await self.loop.run_in_executor(None, self.task.read,
                                                       READ_ALL_AVAILABLE)
                self.last_read = time.monotonic()
                data = np.array(data)
            else:
                data = None
            self.reading = False
            return data
Ejemplo n.º 20
0
def collect_s11_sample():
    # Prompt the user for the name of the sample.
    sample_id = input("Enter a name for the sample: ")

    # Set the NI MyDAQ to output 3.3 VDC on analog channel 0.
    with Task() as task:
        task.ao_channels.add_ao_voltage_chan("myDAQ1/ao0")
        task.write([3.3], auto_start=True)
    
    # Prepare an empty list to contain the data.
    sample = []

    # Perform an S11 measurement on every pin permutation (256)
    for permutation in range(256):
        print("Performing S11 measurement on permutation " + str(permutation) + " of 256.")

        # Add an empty list to the sample list.
        sample.append([])

        # Write to the SIPO registers on the PCB to set the relays.
        with Task() as task:
            task.do_channels.add_do_chan("myDAQ1/port0/line0:2", line_grouping = LineGrouping.CHAN_FOR_ALL_LINES)

            # Convert the permutation into an 8-bit binary string.
            binary = format(permutation, "08b")

            # Zero-out the channels to start.
            task.write(0, 2)

            # Write each bit to the shift register.
            for bit in binary:
                if bit == "1":
                    task.write(1, 2)
                    task.write(3, 2)
                else:
                    task.write(0, 2)
                    task.write(2, 2)

            # Cycle the register clock to load the parallel register.
            task.write(4, 2)
            task.write(0, 2)
        
        # Delay for 700 ms to account for relay bounce.
        sleep(0.70)

        # Utilize the Keysight E5063A ENA to collect an S11 measurement.
        resource_manager = ResourceManager()
        ENA5063 = resource_manager.open_resource("ENA5063")
        ENA5063.write(':INITiate1:CONTinuous %d' % (1))
        ENA5063.write(':CALCulate1:PARameter1:DEFine %s' % ('S11'))
        ENA5063.write(':CALCulate1:PARameter1:SELect')
        ENA5063.write(':TRIGger:SEQuence:SOURce %s' % ('MANual'))
        ENA5063.write(':TRIGger:SEQuence:SINGle')
        ENA5063.write('*OPC')
        ENA5063.write(':INITiate1:CONTinuous %d' % (0))
        ENA5063.write(':CALCulate1:SELected:FORMat %s' % ('MLOGarithmic'))
        ENA5063.write(':FORMat:DATA %s' % ('REAL'))
        ENA5063.write(':FORMat:BORDer %s' % ('SWAPped'))
        measurement = ENA5063.query_binary_values(':CALCulate1:SELected:DATA:FDATa?','d',False)
        ENA5063.close()
        resource_manager.close()

        # The measurement data is returned with 0.0 in odd-indexed elements.
        # We need to iterate over the array and remove these elements before
        # adding them to the data list.
        for j in range(len(measurement)): 
            if j % 2 == 0: sample[permutation].append(measurement[j])

    # Record the data by writing it to a .csv file and storing it in data_raw
    with open("data_raw/" + sample_id + ".csv", mode = "w", newline = "") as file:
        writer(file).writerows(sample)

    # Prompt the user to give the part number for the sample so that it may
    # be added to that device's RMSE dataset.
    device = input("Enter the part number for the device: ")

    baseline = []
    # Use the empty_socket.csv dataset as the baseline for the RMSE calculation.
    with open("data_raw/empty_socket.csv") as file:
        data = reader(file)
        
        for idx, row in enumerate(data):
            baseline.append([])
            for element in row:
                baseline[idx].append(float(element))

    # Compute the Root Mean Squared Error (RMSE) for the sample.
    rmse = []
    for idx, _ in enumerate(sample):
        test    = sample[idx]
        control = baseline[idx]

        # Calculate the squared error
        squared_error = 0
        for jdx, _ in enumerate(test):
            squared_error += (test[jdx] - control[jdx]) ** 2

        # Divide by the length of the row to get the "mean" squared error.
        mean_se = squared_error / len(test)

        # Take the square root of the mean squared error.
        rmse.append(sqrt(mean_se))

    # Append this data to the dataset for the indicated device.
    with open("data_rmse/" + device + ".csv", mode = "a", newline = "") as file:
        writer(file).writerow(rmse)
import nidaqmx
from nidaqmx import Task
from nidaqmx.constants import AcquisitionType, Edge, VoltageUnits, TerminalConfiguration
import numpy as np
from nidaqmx.task import InStream
from nidaqmx.stream_readers import AnalogSingleChannelReader
import time
import matplotlib.pyplot as plt
import os
sample_rate = 100
number_sample = 3000
# init Task
task = Task()
# config Task
task.ai_channels.add_ai_voltage_chan("Dev1/ai0",
                                     terminal_config=TerminalConfiguration.RSE,
                                     min_val=-2.0,
                                     max_val=2.0,
                                     units=VoltageUnits.VOLTS)

task.timing.cfg_samp_clk_timing(sample_rate,
                                active_edge=Edge.RISING,
                                sample_mode=AcquisitionType.CONTINUOUS,
                                samps_per_chan=number_sample)

# getting and handling data
print("Start Reading...")
print("Start Wraping Task Into Instream...")
in_stream = InStream(task)
arr_np_data = np.empty(shape=(number_sample, ), dtype=np.float64)