Main Content

Acquire Data in the Background

This example shows how to acquire data in the background using callbacks while MATLAB continues to run.

A background acquisition depends on callbacks to allow your code to access data as the hardware acquires it and to react to any errors as they occur. In this example, you acquire data from an NI 9205 device with ID cDAQ1Mod1 using the ScansAvailableFcnCount property to trigger the function call defined by the ScansAvailableFcn property.

Create an NI DataAcquisition object with an analog input voltage channel on cDAQ1Mod1:

d = daq("ni");
ch = addinput(d,"cDAQ1Mod1","ai0","Voltage");

Create a simple callback function to plot the acquired data and save it as plotMyData.m in your working directory. Enter the following code in the file:

 function plotMyData(obj,evt)
% obj is the DataAcquisition object passed in. evt is not used.
     data = read(obj,obj.ScansAvailableFcnCount,"OutputFormat","Matrix");
     plot(data)
 end

Set the callback function property to use your function.

d.ScansAvailableFcn = @plotMyData;

Start the acquisition to run for 5 seconds in the background.

start(d,"Duration",5))

Speak into the microphone and watch the plot. It updates 10 times per second.

Related Topics