Examples
Each example is a complete script. They are run by the tests of the package against a double of the driver, so they stay correct; on a computer with an NI device, change the device names and run them.
Discover the hardware
"""List what the computer's NI hardware offers, without creating any task."""
from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, NIDAQSystem
def main():
system = NIDAQSystem()
report = {}
for device in system.devices():
report[device] = {
'analog inputs': system.channels(device, ChannelKind.AI),
'analog outputs': system.channels(device, ChannelKind.AO),
'voltage ranges (V)': system.ai_voltage_ranges(device),
'terminals': system.terminals(device),
'max analog input rate (Hz)': system.ai_max_rate(device, multi_channel=False),
}
return report
if __name__ == '__main__':
for device, properties in main().items():
print(device, properties)
Acquire analog inputs
"""Acquire a block of voltages on two channels and read it as a (channels, samples) array."""
from nidaqmx.constants import TerminalConfiguration
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AIVoltage, AnalogInputTask, ClockSettings, TaskConfig)
def main():
config = TaskConfig(
channels=[AIVoltage('Dev1/ai0', min_val=-5., max_val=5., terminal_config=TerminalConfiguration.DIFF),
AIVoltage('Dev1/ai1', min_val=-5., max_val=5., terminal_config=TerminalConfiguration.DIFF)],
timing=ClockSettings(rate=10_000., samples=1000)) # 1000 samples per channel, 0.1 s
with AnalogInputTask(config) as task: # the task is released when the block is left, whatever happens
task.start()
data = task.read_analog() # float64, shaped (2, 1000); waits for the end of the acquisition
task.stop()
return data
if __name__ == '__main__':
print(main().mean(axis=1))
Wait for a trigger
"""Wait for an edge on a PFI terminal before acquiring."""
from nidaqmx.constants import Edge
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AIVoltage, AnalogInputTask, ChannelKind, ClockSettings, DigitalEdgeTrigger, NIDAQSystem, TaskConfig)
def main(device='Dev2'):
system = NIDAQSystem()
if not system.supports_start_trigger(device, ChannelKind.AI):
raise RuntimeError(f'{device} cannot wait for a start trigger')
pfi = next(terminal for terminal in system.terminals(device) if 'PFI' in terminal) # e.g. /Dev2/PFI0
config = TaskConfig(channels=[AIVoltage(f'{device}/ai0')],
timing=ClockSettings(rate=1000., samples=100),
trigger=DigitalEdgeTrigger(pfi, edge=Edge.RISING))
with AnalogInputTask(config) as task:
task.start() # armed, nothing is acquired until the edge arrives
return task.read_analog(timeout=10.) # give the experiment time to send its edge
if __name__ == '__main__':
print(main().shape)
Generate analog outputs
"""Set a voltage, then play a waveform clocked by the device."""
import numpy as np
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AOVoltage, AnalogOutputTask, ClockSettings, TaskConfig)
def main():
channel = AOVoltage('Dev2/ao0', min_val=-5., max_val=5.)
with AnalogOutputTask(TaskConfig(channels=[channel])) as task:
task.write_levels([1.5]) # a DC level, applied at once
waveform = np.sin(np.linspace(0, 2 * np.pi, 100))
config = TaskConfig(channels=[channel], timing=ClockSettings(rate=1000., samples=len(waveform)))
with AnalogOutputTask(config) as task:
task.write_analog(waveform) # written to the buffer, nothing is output yet
task.start() # 100 ms of sine
return waveform
if __name__ == '__main__':
main()
Count pulses with a clock
"""Count the edges received during one tick of a clock generated by another counter."""
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
CICountEdges, COPulseFreq, ClockSettings, CounterInputTask, CounterOutputTask, ImplicitTiming, TaskConfig,
TaskGroup, counter_output_terminal)
def main(frequency=100.):
clock_config = TaskConfig(channels=[COPulseFreq('Dev2/ctr1', frequency=frequency)],
timing=ImplicitTiming()) # pulses until stopped
counter_config = TaskConfig(
channels=[CICountEdges('Dev2/ctr0')],
timing=ClockSettings(rate=frequency, samples=1, source=counter_output_terminal('Dev2/ctr1')))
with TaskGroup(CounterInputTask(counter_config), CounterOutputTask(clock_config)) as group:
counter, clock = group.tasks
group.start() # in the given order: the counter is armed first and waits for the clock
counts = counter.read_counter()[0, 0] # edges since the start, at the first tick
return counts * frequency # counts per second
if __name__ == '__main__':
print(main())
Be told when samples are ready
"""Acquire 100 samples and be told as each block of 10 is ready."""
from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AIVoltage, AnalogInputTask, ClockSettings, TaskConfig, TaskListener)
class Recorder(TaskListener):
"""What a task tells: the driver calls these from threads of its own, not from yours."""
def __init__(self):
self.blocks = []
self.status = None
def on_samples_ready(self, data): # data is shaped (channels, samples); keep it short, hand it over
self.blocks.append(data)
def on_done(self, status): # 0 when the task ended normally
self.status = status
def main():
config = TaskConfig(channels=[AIVoltage('Dev1/ai0')], timing=ClockSettings(rate=1000., samples=100))
recorder = Recorder()
with AnalogInputTask(config) as task:
task.add_listener(recorder)
task.start(notify_every=10) # one block of 10 samples at a time
# ... wait, for example with a threading.Event set from on_done, then use recorder.blocks
return recorder