Transition Your Code from Session to DataAcquisition Interface
This topic helps you transition your code from the session interface to the DataAcquisition interface.
Transition Common Workflow Commands
This table lists the session interface commands for common workflows and their corresponding DataAcquisition interface commands.
To do this | Session Commands | DataAcquisition Commands |
---|---|---|
Find supported hardware available to your system |
daq.getDevices | |
Reset toolbox to initial state |
daqreset | |
Create interface object |
s = daq.createSession('ni') |
d = |
Add analog input channel |
addAnalogInputChannel(s,'Dev1',1,'Voltage') |
|
Add analog output channel |
addAnalogOutputChannel(s,'Dev1',0,'Current') |
|
Add digital input line |
addDigitalChannel... (s,'Dev1','Port0/Line0:1','InputOnly') |
addinput(d,"Dev1","port0/line1","Digital"); |
Add counter input channel |
addCounterInputChannel... (s,'Dev1','ctr0','EdgeCount') |
addinput(d,"Dev1","ctr0","EdgeCount"); |
Add counter output channel |
addCounterOutputChannel... (s,'Dev1','ctr0','PulseGeneration') |
addoutput(d,"Dev1","ctr0","PulseGeneration"); |
Set data scan rate |
s.Rate = 48000 |
d.Rate = 48000; |
Queue data for output |
queueOutputData(s,outputSignal) | Necessary only for background operation.
|
Start synchronous foreground operation that blocks MATLAB® | Acquire input signal. s.DurationInSeconds = 5; inData = startForeground(s); | Duration is an input argument to the
read
function.inData = |
Generate output signal. queueOutputData(s,outputSignal); startForeground(s); | Output data is provided directly to the
write
function.
| |
Generate and acquire signals simultaneously. queueOutputData(s,outputSignal); inData = startForeground(s); | Use inData = | |
Start asynchronous background read operation that runs without blocking MATLAB |
s.DurationInSeconds = 5; startBackground(s) |
start(d,"Duration",seconds(5)) ⋮ inData = read(d,"all") |
Start asynchronous background write operation that runs without blocking MATLAB |
queueOutputData(s,outputSignal); startBackground(s); | |
Start continuous background operation |
s.IsContinuous = true; inData = startBackground(s); | Continuous operation is specified by the
start
function.
|
Start continuous background write operation |
lh = addlistener(s,'DataRequired',@queueMoreData);
s.IsContinuous = true;
queueOutputData(s,outputSignal);
startBackground(s); | If data is preloaded, generation begins with
the If
data is not preloaded, generation begins with the
|
Configure callbacks |
listenDA = addlistener(s,'DataAvailable',@logData); listenDR = addlistener(s,'DataRequired',@queueMoreData); listenEO = addlistener(s,'ErrorOccurred',@handleError); |
d.ScansAvailableFcn = @logData; d.ScansRequiredFcn = @writeMoreData; d.ErrorOccurredFcn = @handleError; |
Specify external trigger |
addTriggerConnection... (s,'External','Dev3/PFI0','StartTrigger'); |
|
Specify input signal range |
ch = addAnalogInputChannel... (s,'Dev1',1,'Voltage'); ch.Range = [-5 5]; |
ch = addinput(d,"Dev1","ai4","Voltage"); ch.Range = [-5 5]; |
Acquire Analog Data
Session Interface
Using the session interface, you create a vendor session and add channels to the session. You can use any device or chassis from the same vendor available to your system and can add a combination of analog, digital, and counter input and output channels. All the channels operate together when you start the session.
Find hardware available to your system.
d = daq.getDevices
Create a session for National Instruments™ devices.
s = daq.createSession('ni');
Set the session scan rate to 8000.
s.Rate = 8000
Add an analog input channel for the device with ID Dev1 for voltage measurement, and then start the acquisition.
addAnalogInputChannel(s,'Dev1',1,'Voltage'); startForeground(s);
DataAcquisition Interface
Find hardware available to your system.
devs = daqlist
Create a DataAcquisition for National Instruments devices.
d = daq("ni");
Set the DataAcquisition scan rate to 8000.
d.Rate = 8000
Add an analog input channel for the device with ID
Dev1
for voltage measurement, and then start the acquisition.addinput(d,"Dev1","ai1","Voltage"); data = read(d,4000);
Scan results are returned to the timetable
data
.
Use Triggers
Acquire analog data using hardware triggers.
Session Interface
You can specify an external event to trigger data acquisition using the session interface.
Create a session and add two analog input channels.
s = daq.createSession('ni'); ch = addAnalogInputChannel(s,'Dev1',0:1,'Voltage');
Configure the terminal and range of the channels in the session.
ch(1).TerminalConfig = 'SingleEnded'; ch(1).Range = [-10.0 10.0]; ch(2).TerminalConfig = 'SingleEnded'; ch(2).Range = [-10.0 10.0];
Create an external trigger connection and set the trigger to run one time.
addTriggerConnection(s,'External','Dev1/PFI0','StartTrigger'); s.Connections(1).TriggerCondition = 'RisingEdge'; s.TriggersPerRun = 1;
Set the rate and the duration of the acquisition.
s.Rate = 50000; s.DurationInSeconds = 0.01;
Acquire data in the foreground and plot the data.
[data,timestamps] = startForeground(s); plot(timestamps,data)
DataAcquisition Interface
Create a DataAcquisition and add two analog input channels.
d = daq("ni"); ch = addinput(d,"Dev1",0:1,"Voltage");
Configure the terminal configuration and range of the channels in the DataAcquisition.
ch(1).TerminalConfig = "SingleEnded"; ch(1).Range = [-10.0 10.0]; ch(2).TerminalConfig = "SingleEnded"; ch(2).Range = [-10.0 10.0];
Create an external trigger connection and set the trigger to run one time.
addtrigger(d,"Digital","StartTrigger","Dev1/PFI0","External"); d.DigitalTriggers(1).Condition = "RisingEdge"; d.NumDigitalTriggersPerRun = 1;
Set the scan rate of the acquisition.
d.Rate = 50000;
Acquire data in the foreground for 0.01 seconds and plot the data from all channels.
data = read(d,seconds(0.01)); plot(data.Time, data.Variables)
Initiate an Operation When Number of Scans Exceeds Specified Value
You can specify your acquisition to watch for a specified number of scans to occur and then initiate some operation.
Session Interface
The session interface uses listeners and events to trigger certain
actions. The NotifyWhenDataAvailableExceeds
property can fire a DataAvailable
event. A
listener defines the operation to execute at that time.
Create an acquisition session, add an analog input channel.
s = daq.createSession('ni'); addAnalogInputChannel(s,'Dev1','ai0','Voltage');
Set the scan rate to 800,000 scans per second, which automatically sets the
DataAvailable
notification to automatically fire 10 times per second.s.Rate = 800000; s.NotifyWhenDataAvailableExceeds
ans = 80000
Increase
NotifyWhenDataAvailableExceeds
to 160,000.s.NotifyWhenDataAvailableExceeds = 160000;
Add a listener to determine the function to call when the event occurs.
L = addlistener(s,'DataAvailable', ... @(src,event)readAndLogData(src));
DataAcquisition Interface
The DataAcquisition interface uses callback functions that execute at
occurrences determined by certain properties. The
ScansAvailableFcnCount
property determines
when to initiate the callback function defined by
ScansAvailableFcn
.
Create a DataAcquisition interface and add an analog input channel.
d = daq("ni"); ch = addinput(d,"Dev1",1,"Voltage");
Set the scan rate to 800,000 scans per second, which automatically adjusts the
ScansAvailableFcnCount
property.d.Rate = 800000; d.ScansAvailableFcnCount
80000
Increase
ScansAvailableFcnCount
to 160,000.d.ScansAvailableFcnCount = 160000;
Identify a callback function for when the count occurs.
d.ScansAvailableFcn = @readAndLogData;
Analog Output Generator Code
To compare session interface code and DataAcquisition interface code you can use the code generated by the Analog Output Generator in MATLAB releases R2019b and R2020a. In both these examples, the generator created a 10 Hz test signal sine wave for 1 second on a single channel of a National Instruments USB-6211.
%% Auto-generated by Data Acquisition Toolbox Analog Output Generator in MATLAB R2020a. %% Create DataAcquisition Object % Create a DataAcquisition object for the specified vendor. d = daq("ni"); %% Add Channels % Add channels and set channel properties, if any. addoutput(d,"Dev1","ao0","Voltage"); %% Set DataAcquisition Rate % Set scan rate. d.Rate = 250000; %% Define Test Signal % Create a test sine wave signal of specified peak-to-peak amplitude for each % channel. amplitudePeakToPeak_ch1 = 20; sineFrequency = 10; % 10 Hz totalDuration = 1; % 1 seconds outputSignal = []; outputSignal(:,1) = createSine(amplitudePeakToPeak_ch1/2, ... sineFrequency, d.Rate, "bipolar", totalDuration); outputSignal(end+1,:) = 0; %% Generate Signal % Write the signal data. write(d,outputSignal); %% Clean Up % Clear all DataAcquisition and channel objects. clear d outputSignal %% Create Test Signal % Helper function for creating test sine wave signal. function sine = createSine(A, f, sampleRate, type, duration) numSamplesPerCycle = floor(sampleRate/f); T = 1/f; timestep = T/numSamplesPerCycle; t = (0 : timestep : T-timestep)'; if type == "bipolar" y = A*sin(2*pi*f*t); elseif type == "unipolar" y = A*sin(2*pi*f*t) + A; end numCycles = round(f*duration); sine = repmat(y,numCycles,1); end
%% Auto-generated by Data Acquisition Toolbox Analog Output Generator in MATLAB R2019b %% Create Data Acquisition Session % Create a session for the specified vendor. s = daq.createSession('ni'); %% Set Session Properties % Set properties that are not using default values. s.Rate = 250000; %% Add Channels to Session % Add channels and set channel properties. addAnalogOutputChannel(s,'Dev1','ao0','Voltage'); %% Define Test Signal % Create a test sine wave signal of specified peak-to-peak amplitude for each % channel. amplitudePeakToPeak_ch1 = 20; sineFrequency = 10; % 10 Hz totalDuration = 1; % 1 seconds outputSignal(:,1) = createSine(amplitudePeakToPeak_ch1/2, ... sineFrequency, s.Rate, 'bipolar', totalDuration); outputSignal(end+1,:) = 0; %% Queue Signal Data % Make signal data available to session for generation. queueOutputData(s,outputSignal); %% Generate Signal % Start foreground generation startForeground(s); %% Clean Up % Clear the session and channels. clear s outputSignal %% Create Test Signal % Helper function for creating test sine wave signal. function sine = createSine(amplitude, frequency, sampleRate, type, duration) sampleRatePerCycle = floor(sampleRate/frequency); period = 1/frequency; s = period/sampleRatePerCycle; t = (0 : s : period-s)'; if strcmpi(type, 'bipolar') y = amplitude*sin(2*pi*frequency*t); elseif strcmpi(type, 'unipolar') y = amplitude*sin(2*pi*frequency*t) + amplitude; end numCycles = round(frequency*duration); sine = repmat(y, numCycles, 1); end
Previous Interface Help
The DataAcquisition interface is supported in R2020a and later. If you are using an earlier release, use the session interface instead. For more information and examples of the session interface, see Data Acquisition Toolbox Documentation (R2019b).