MATLAB: NIDAQ continuous and background acquisition

acquisitionbackgroundcontinuousdaqdataData Acquisition Toolboxnational instrumentsni

Hello everybody,
I'm trying to acquire and store data from a CompactDAQ from National Instruments. The configuration of the device itselt and the visualization of the data is pretty straightforward, but I'm having trouble in store this data in a matrix that I will be able to access after the acquisition is over.
I'm connecting the device as follows:
s=daq.createSession('ni');
s.addAnalogInputChannel('cDAQ1Mod2', 0, 'voltage');
s.Rate=2000;
s.DurationInSeconds = 60;
to plot the data in real time I use the following lines of code:
lh = s.addlistener('DataAvailable', @plotData);
function plotData(src,event)
plot(event.TimeStamps, event.Data)
end
and then I start it in background (I need to acquire data in background in order to perform other tasks at the same time):
s.startBackground();
This seems to work fine for the real time problem, but I'm having trouble to define a callback function that will store all data acquired into a matrix or structure. I'm sure that this is a quite basic problem.
I want to thank you all in advance for your time.

Best Answer

Hi Nuno,
There are number of ways to achieve this:
1) Use some global data
function acquireData
global data
s = daq.createSession('ni');
s.addAnalogInputChannel('cDAQ1Mod1',0,'voltage')
s.Rate = 2000
s.DurationInSeconds = 5
lh = s.addlistener('DataAvailable',@plotData);
s.startBackground();
% Do something
while(~s.IsDone)
end
close(gcf);
plot(data); % plot global data
function plotData(src,event)
persistent tempData;
global data
if(isempty(tempData))
tempData = [];
end
plot(event.TimeStamps, event.Data)
tempData = [tempData;event.Data];
data = tempData;
end
2) Use NotifyWhenDataAvailableExceeds property (This decides when 'DataAvailable' is called. So if you don't want a live plot then this is suitable. Just set this to s.Rate * s.DurationInSeconds.
and have a callback for DataAvailable as:
function collectData(src,event)
time = event.TimeStamps;
data = event.Data;
plot(time,data)
save log.mat data time
disp(Background Acquisition complete);
end
This should save the data to a matfile.
3) Write Data to a file:
function acquireData
s = daq.createSession('ni');
s.addAnalogInputChannel('cDAQ1Mod1',0,'voltage')
s.Rate = 2000
s.DurationInSeconds = 5
fid = fopen('log.csv','w');
lh = s.addlistener('DataAvailable',@(src,event)saveData(fid,event));
s.startBackground();
while(~s.IsDone)
end
function saveData(fid,event)
time = event.TimeStamps;
data = event.Data;
plot(time,data)
fprintf(fid,'%f,%f\n',time,data)
end
Related Question