Main Content

Generate Signals in the Background Continuously

This example shows how to continuously generate signals. A continuous background generation depends on callbacks to enable continuous queuing of data and to react to any errors as they occur. In this example, you generate from an NI 9263 device with ID cDAQ1Mod2.

A callback function is configured to run when a certain number of scans are required.

Create an NI DataAcquisition object and add an analog output voltage channel on cDAQ1Mod2:

d = daq("ni");
addoutput(d,"cDAQ1Mod2","ao0","Voltage");

Specify the channel ID on NI devices using a terminal name, like 'ao1', or a numeric equivalent like 1.

Queue a column of output data.

preload(d,linspace(1,10,1000)');

Create a simple callback function to load data 1000 samples at a time. Save the function file as loadMoreData.m in your working folder:

function loadMoreData(obj,evt)
    % obj is the DataAcquisition object passed in. evt is not used.
    write(obj,linspace(1,10,1000)');
end

Define the ScansRequiredFcn to call your function loadMoreData:

d.ScansRequiredFcn = @loadMoreData;

This callback is executed whenever the number of queued scans falls below the threshold defined by the property ScansRequiredFcnCount. The default threshold is defined at 0.5 seconds of data at the default scan rate. In other words, with a default Rate at 1000 scans per second, the default ScansRequiredFcnCount value is 500. As your device generates an output signal, when the queued data falls below 500 scans, it triggers the ScansRequiredFcn.

d.ScansRequiredFcnCount
ans = 

    500

Generate the continuous output signal:

start(d,"Continuous")

You can execute other MATLAB® commands while the generation is in progress. In this example, issue a pause, which causes the MATLAB command line to wait for you to press any key.

pause

Tip

If you want to continuously generate a repeating or periodic output, preload the waveform data, and use

start(d,"RepeatOutput")

Related Topics