Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Using the DAQ output and calling it as an external function

Asked by Mike on 20 Jan 2012

I am using 2011b 32bit, I have a main body of code and want to use the DAQ-TB to call an NI-USB based DAQ to generate signals. I want to call the DAQ function from my main program, execute it to generate a signal continuously, and return to the main function to conduct other analysis and also use the DAQ to make measurements. I want to return and change the DAQ output depending on the measurements made and other data related to the DAQ output. I also have to access other hardware. The waveform generator works fine and runs continuously while I am in that script, but when I call it from an external script it shuts down. This is the script I want to call from the main body:

s = daq.createSession('ni');

s.addAnalogOutputChannel('Dev1', 0, 'Voltage');

s.Rate = 2e6; %in Hz

Dur = .5; % In seconds, but system polls for more data, so it doesn't matter?

Fr = 5e3; % In Hz

signalVoltPk = 2; % In peak voltage

squareWv = 0; % Set to 1 for square wave.

Npts = round(Dur*s.Rate);

x = (0:(Npts-1))/s.Rate;

data = signalVoltPk*sin(Fr*2*pi*x); data=data(:);

if squareWv == 1; data(data < 0) = - signalVoltPk; % Convert sin wave to square wave data(data > 0) = signalVoltPk; end

lh = s.addlistener('DataRequired', @(src, event)src.queueOutputData(data));

s.queueOutputData(data);

s.IsContinuous = true;

s.startBackground();

When I look through the DAQ function generator included with the toolbox, all the calls are to internal functions.... Is that necessary?

Thanks

0 Comments

Mike

1 Answer

Answer by Manisha on 20 Jan 2012
Accepted answer

Hi Mike,

It seems that your session object is going out of scope when you call your code as a function from your main script.

From doc:

"A variable goes out of scope when you explicitly clear it or when its function ends."

When the session object is deleted, it stops any acquisition or generation associated with it. One way to solve this would be to return the session object from your function, so that it is not deleted.

%% **mainscript.m**
..
session = waveform_generator();
....
%% **waveform_generator.m **
function session = waveform_generator
..
end

Hope this helps,

Manisha

1 Comment

Mike on 20 Jan 2012

:-) But of course.... With the instrument control toolbox I didn't have to deal with this problem... Do you have a link to the location in the document?

Great gratitude and have a good weekend

Manisha

Contact us