Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ Below is the list of instruments included in this plugin
Actuators
+++++++++

* **NIDAQmx**: General generation (voltage / current) with National Instrument materials
* **NIDAQmx**: One analog output (voltage / current) of a National Instrument device, set one point at a time
* **NIDAQmx_DO**: One digital output line (0 / 1, or a pulse to trigger an acquisition)
* **NIDAQmx_RampOutput**: A quantity driven by an analog output, changed by voltage ramps timed by a counter used as a
clock (value = voltage x conversion factor); several axes (x, y, z) can share the clock

Expand Down
1 change: 1 addition & 0 deletions docs/source/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ This user guide will first explain how to use these plugins, and then detail how
user_guide/ai_use
user_guide/ramp_output_use
user_guide/nidaqmx_viewer_use
user_guide/nidaqmx_actuator_use
user_guide/config_files

For any other use, you will need to create your own move or viewer based on this plugin. See the :ref:`create_plugin` guide for a detailed procedure.
Expand Down
35 changes: 35 additions & 0 deletions docs/source/user_guide/nidaqmx_actuator_use.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
Generic actuators NIDAQmx and NIDAQmx_DO
========================================

Two actuators drive **one output** of an NI device: ``NIDAQmx`` (``DAQ_Move_NIDAQmx``), an analog output (a level in
volts or amperes), and ``NIDAQmx_DO`` (``DAQ_Move_NIDAQmx_DO``), a digital line (0 or 1). They set the output to a value
on demand, one point at a time: there is no clock and no waveform (for voltage ramps, see ``NIDAQmx_RampOutput``). To
drive several outputs, use one actuator for each. The analog one has the *Simple* user interface (a value and a button);
the digital one has the *Binary* interface (one button for each level).

How to use it
-------------

1. Choose the **Output** in the list: the analog outputs (``Dev1/ao0``) of the computer for ``NIDAQmx``, the digital
lines (``Dev1/port0/line0``) for ``NIDAQmx_DO``.
2. For an analog output, choose the **Type** (``voltage`` or ``current``) and the range of the output (**Min** and
**Max**, in V or A). The unit of the actuator follows the type.
3. Move the actuator to the level you need. A level outside the range is cut to it, and the plugin says so.

The level of an output cannot be read back from the device, so the value shown is the last level written. The output is
set to 0 (0 V, 0 A or low) when the actuator starts, when you choose another output or another type (the previous
output goes to 0 before the new one is driven) and when the actuator closes.

Digital lines (``NIDAQmx_DO``)
------------------------------

A line is high for a value of 1 and low for 0. The *Pulse* option is for triggering something: a move to 1 then sets
the line high for the **Pulse width** (in ms) and sets it low again, so the position is 0 again afterwards (it is the real level of the line). As that is too fast to see, each pulse is written in the log and counted in the read-only **Pulses sent**. Wire the line
to a PFI terminal of the device (or of the chassis) and use that terminal as the *Terminal* of the start trigger of a
module of the generic viewers (:doc:`nidaqmx_viewer_use`) to start an acquisition with it.

Using the same device with other plugins
----------------------------------------

An output is used by one task only: the same channel cannot be driven by two actuators, and the driver tells so (the
resource is reserved). Other channels, and the inputs of the same device, remain free.
19 changes: 19 additions & 0 deletions docs/source/user_guide/nidaqmx_viewer_use.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,22 @@ written, and is back to normal when it worked. After a failure the menu goes bac
that is not in the tree.

A file that cannot be read gives an error that names the file and the entry that is wrong.

Digital input lines (``NIDAQmx_DI``)
------------------------------------

``DAQ_1DViewer_NIDAQmx_DI`` (in the 1D viewers, as ``NIDAQmx_DI``) is the same viewer for the digital input lines of
a device (``Dev1/port0/line0``), as 1D traces: a line is 0 or 1, so there is no mean and no 0D display. It differs
from the analog viewer in a few points:

* The group ``Lines`` replaces ``Channels``: *Add* lists the lines of the computer, and a line has no type nor range,
only its ``read`` box.
* The group of each module (``Modules``) is the same, with the frequency and the clock, but the start trigger is
``none`` or ``digital edge`` only: a digital input has no analog trigger. ``internal`` is the sample clock of the
digital task itself (``/Dev1/di/SampleClock``), which exists on the devices that can time their digital lines. If the
driver refuses it, choose a clock source: a PFI terminal wired to a clock, or the clock of another module. The
sample clock of an analog input (``/Dev1/ai/SampleClock``) is a different clock: it only runs while an analog
task of that device runs, at its rate, which is what you want to read lines in step with analog channels.
* Each module has its own task and gives its own data, named ``NI DI <module>``, with the lines as traces labelled
with their names.
* There is no live mode and no configuration file in this version.
61 changes: 54 additions & 7 deletions src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,57 @@
from ..hardware.national_instruments.NIDAQmx_Move import DAQ_NIDAQmx_Actuator
"""Generic actuator for one analog output of an NI device: a level in volts or amperes, set on demand.

There is no clock and no waveform (for voltage ramps, see ``DAQ_Move_NIDAQmx_RampOutput``; for a digital line,
``DAQ_Move_NIDAQmx_DO``). The common behaviour (zero at start, change and close, position = last level written) is in
``OutputActuator``.
"""
import numpy as np
from pymodaq.control_modules.daq_move_ui.utils import UiType
from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main
from pymodaq.utils.daq_utils import ThreadCommand

class DAQ_Move_NIDAQmx(DAQ_NIDAQmx_Actuator):
"""
Plugin for basic current or voltage control with NI modules (plugged in NI cDAQ or NI-USB). (in process)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (AnalogOutputTask, AOCurrent, AOVoltage,
ChannelKind, TaskConfig)
from pymodaq_plugins_daqmx.hardware.national_instruments.output_actuator import OutputActuator

ANALOG_TYPES = {'voltage': (AOVoltage, 'V'), 'current': (AOCurrent, 'A')} # type -> channel of the API, unit


class DAQ_Move_NIDAQmx(OutputActuator):
"""One analog output: the level in V or A, cut to the range of the output."""
_controller_units = 'V'
_epsilons = [1e-3]
ui_type = UiType.SIMPLE # a value to type and a button to set it
output_kind = ChannelKind.AO
rebuild_on = ('channel', 'type', 'min_val', 'max_val')
params = [
{'title': 'Output:', 'name': 'channel', 'type': 'list', 'limits': [], 'tip': 'An analog output (Dev1/ao0)'},
{'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': list(ANALOG_TYPES), 'value': 'voltage'},
{'title': 'Min:', 'name': 'min_val', 'type': 'float', 'value': -10., 'suffix': 'V',
'tip': 'Lowest level of the output; the level asked is cut to the range'},
{'title': 'Max:', 'name': 'max_val', 'type': 'float', 'value': 10., 'suffix': 'V'},
] + comon_parameters_fun(False, axis_names=OutputActuator._axis_names, epsilon=_epsilons)

def make_task(self):
cls = ANALOG_TYPES[self.settings['type']][0]
return AnalogOutputTask(TaskConfig(channels=[cls(self.settings['channel'], self.settings['min_val'],
self.settings['max_val'])]))

def send(self, level: float) -> None:
self.controller.write_analog(float(level))
self.level = float(level)

def show_settings(self) -> None:
unit = ANALOG_TYPES[self.settings['type']][1]
for name in ('min_val', 'max_val'):
self.settings.child(name).setOpts(suffix=unit)
self.axis_unit = unit

def clip(self, level: float) -> float:
clipped = float(np.clip(level, self.settings['min_val'], self.settings['max_val']))
if clipped != level:
self.emit_status(ThreadCommand('outofbounds'))
return clipped


if __name__ == '__main__':
main(__file__)
57 changes: 57 additions & 0 deletions src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_DO.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Generic actuator for one digital output line of an NI device: 0 (low) or 1 (high), or a pulse.

The common behaviour (zero at start, change and close, position = last level written) is in ``OutputActuator``.
"""
import time

from pymodaq.control_modules.daq_move_ui.utils import UiType
from pymodaq.control_modules.move_utility_classes import DataActuator, comon_parameters_fun, main
from pymodaq.utils.daq_utils import ThreadCommand

from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, DigitalOut, DigitalTask, TaskConfig
from pymodaq_plugins_daqmx.hardware.national_instruments.output_actuator import OutputActuator


class DAQ_Move_NIDAQmx_DO(OutputActuator):
"""One digital line: high for a value of 1 (from 0.5 on), low for 0. With ``pulse``, a move to 1 sets the line high
for ``pulse_width`` ms and then low again, to trigger something (wire the line to a PFI terminal)."""
_controller_units = ''
_epsilons = [0.1]
ui_type = UiType.BINARY # two buttons: one for each level
output_kind = ChannelKind.DO
params = [
{'title': 'Line:', 'name': 'channel', 'type': 'list', 'limits': [], 'tip': 'A digital line (Dev1/port0/line0)'},
{'title': 'Pulse:', 'name': 'pulse', 'type': 'bool', 'value': False,
'tip': 'A move to 1 sets the line high for the pulse width, then low again'},
{'title': 'Pulse width (ms):', 'name': 'pulse_width', 'type': 'float', 'value': 10., 'min': 0.},
{'title': 'Pulses sent:', 'name': 'pulses', 'type': 'int', 'value': 0, 'readonly': True,
'tip': 'The line is low again after a pulse, so the position does not show it: this counts them'},
] + comon_parameters_fun(False, axis_names=OutputActuator._axis_names, epsilon=_epsilons)

def make_task(self):
return DigitalTask(TaskConfig(channels=[DigitalOut(self.settings['channel'])]))

def send(self, level: float) -> None:
high = bool(level >= 0.5)
self.controller.write_digital(high)
self.level = float(high)

def show_settings(self) -> None:
self.axis_unit = ''

def drive(self, level: float) -> None:
if self.settings['pulse'] and level >= 0.5:
self.send(1.)
time.sleep(self.settings['pulse_width'] * 1e-3)
self.send(0.)
self.target_value = DataActuator(data=0., units=self.axis_unit) # the line is low again
self.settings.child('pulses').setValue(self.settings['pulses'] + 1)
self.emit_status(ThreadCommand('Update_Status', [
f"Pulse {self.settings['pulses']} of {self.settings['pulse_width']:g} ms sent on "
f"{self.settings['channel']}", 'log']))
else:
self.send(level)


if __name__ == '__main__':
main(__file__)
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@

# --- terminals --------------------------------------------------------------------------------------------------

def _exporting_module(terminal: str) -> Optional[str]:
"""The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1``), None for
any other terminal (``/Dev1/PFI0``, a wire). It tells which task has to be started before another one."""
def _exporting_module(terminal: str, subsystem: str = 'ai') -> Optional[str]:
"""The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1`` for the
subsystem ``ai``), None for any other terminal (``/Dev1/PFI0``, a wire). It tells which task has to be started
before another one."""
parts = (terminal or '').split('/')
return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == 'ai' else None
return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == subsystem else None


# what the driver lists as terminals but cannot be a clock or a trigger source
Expand All @@ -63,15 +64,16 @@ def is_clock_source(terminal: str) -> bool:
return _CLOCK_SOURCE.match(terminal) is not None


def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict:
def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str],
trigger_types: List[str] = TRIGGER_TYPES) -> dict:
"""The settings of a module: its frequency, its clock and its start trigger."""
return {'title': module, 'name': module, 'type': 'group', 'children': [
{'title': 'Frequency:', 'name': 'frequency', 'type': 'int', 'value': frequency, 'min': 1,
'tip': 'Sampling rate; with an external clock, the real frequency of that clock (the highest it may have)'},
{'title': 'Clock:', 'name': 'clock', 'type': 'list', 'limits': clocks, 'value': CLOCK_INTERNAL,
'tip': 'The clock of the module, or a terminal (a clock wired in, or the clock that another module exports)'},
{'title': 'Start trigger:', 'name': 'trigger', 'type': 'group', 'children': [
{'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': TRIGGER_TYPES, 'value': 'none'},
{'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': trigger_types, 'value': 'none'},
{'title': 'Terminal:', 'name': 'terminal', 'type': 'list', 'limits': terminals, 'visible': False},
{'title': 'Channel:', 'name': 'channel', 'type': 'list', 'limits': channels, 'visible': False,
'tip': 'A channel of this module (it is acquired) or a dedicated analog trigger terminal'},
Expand Down Expand Up @@ -107,16 +109,28 @@ class DAQ_0DViewer_NIDAQmx(DAQ_Viewer_AIBase):
'limits': [], 'children': []},
]
data_name = 'NI AI'
# what distinguishes the subclasses for other inputs (the digital lines): the kind of channels of the tree (it
# also names the subsystem of the driver that exports the clock and the trigger of a module: ``/Dev1/ai/...``),
# the types of start trigger, and whether there are files
kind = ChannelKind.AI
trigger_types = TRIGGER_TYPES
has_configuration = True

@property
def subsystem(self) -> str:
"""The part of the terminal names that the driver gives to the subsystem of the channels (``ai``, ``di``)."""
return self.kind.value

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
system = NIDAQSystem()
self.settings.child('channels').setLimits(system.all_channels(ChannelKind.AI))
self.settings.child('channels').setLimits(system.all_channels(self.kind))
self.terminals = {device: system.terminals(device) for device in system.devices()} # of each device
self.files = ConfigFiles()
self.loaded = MANUAL # the configuration whose channels are in the tree
self.in_file = () # what the file describes (see `snapshot`), to tell if the tree still is the file
self.refresh_menu()
if self.has_configuration:
self.refresh_menu()

# --- configuration files: menu, load, save ------------------------------------------------------------------

Expand Down Expand Up @@ -228,7 +242,7 @@ def sync_modules(self) -> None:
for module in modules:
lists = self.module_lists(module)
if module not in group.names:
group.addChild(module_group(module, self.settings['frequency'], **lists))
group.addChild(module_group(module, self.settings['frequency'], trigger_types=self.trigger_types, **lists))
continue
self.set_limits(group.child(module, 'clock'), lists['clocks'])
self.set_limits(group.child(module, 'trigger', 'terminal'), lists['terminals'])
Expand Down Expand Up @@ -264,7 +278,7 @@ def module_lists(self, module: str) -> dict:
only the devices that can reach the module offer terminals (see ``reachable_devices``)."""
reachable = self.reachable_devices(module)
others = [m for m in self.modules() if m != module and m in reachable]
own = f'/{module}/ai/'
own = f'/{module}/{self.subsystem}/'
terminals = [t for device in reachable for t in self.terminals.get(device, [])
if not t.startswith(own) and is_signal_terminal(t)]
names = [child.opts['title'] for child in self.settings.child('channels').children()
Expand All @@ -275,8 +289,8 @@ def module_lists(self, module: str) -> dict:
apfi = []
# the clock sources of all the devices, and the sample clock that another module of the tree exports
clocks = ([CLOCK_INTERNAL] + [t for t in terminals if is_clock_source(t)]
+ [f'/{m}/ai/SampleClock' for m in others])
starts = terminals + [f'/{m}/ai/StartTrigger' for m in others]
+ [f'/{m}/{self.subsystem}/SampleClock' for m in others])
starts = terminals + [f'/{m}/{self.subsystem}/StartTrigger' for m in others]
return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)),
'channels': names + apfi}

Expand Down Expand Up @@ -340,7 +354,7 @@ def acquisitions(self) -> List[Acquisition]:
# the parameter of the trigger that names its source depends on the type of trigger
key = {'digital edge': 'terminal', 'analog edge': 'channel'}.get(group['trigger', 'type'])
sources = [clock] + ([group['trigger', key]] if key is not None else [])
waits = tuple(dict.fromkeys(m for m in (_exporting_module(source) for source in sources)
waits = tuple(dict.fromkeys(m for m in (_exporting_module(source, self.subsystem) for source in sources)
if m not in (None, module) and m in by_module))
acquisitions.append(Acquisition(module, channels, group['frequency'],
tuple(c.name for c in channels if c.name in unread), clock, trigger, waits))
Expand Down Expand Up @@ -400,9 +414,9 @@ def commit_settings(self, param: Parameter) -> None:
param = self.own(param)
parent = param.parent()
in_a_channel = parent is not None and parent.parent() is self.settings.child('channels')
if param.name() == 'configuration' and parent is self.settings.child('config'):
if self.has_configuration and param.name() == 'configuration' and parent is self.settings.child('config'):
self.load_configuration()
elif param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI
elif self.has_configuration and param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI
param.opts.update(suffix=button.opts['suffix'])
try:
self.save_configuration(param)
Expand All @@ -411,7 +425,7 @@ def commit_settings(self, param: Parameter) -> None:
param.setValue(Status.ERROR)
self.fail(error)
if param.name() == 'type' and in_a_channel: # the type of a channel: its group is rebuilt
set_type(ChannelKind.AI, parent, param.value())
set_type(self.kind, parent, param.value())
if param.name() == 'units' and in_a_channel: # the units of a temperature: the range follows
update_suffixes(parent)
if param.name() == 'type' and parent is not None and parent.name() == 'trigger':
Expand Down
Loading
Loading