DAQ in background save data to workspace variables

15 views (last 30 days)
I would like to acquire data in the background using a NI 6036e DAQ card. The tutorial here http://www.mathworks.com/help/daq/acquire-analog-input-data.html plots the data, but I would like to store the timestamps and acquisition data as workspace variables for further data processing.
I do not have a background in object oriented programming, so I'm not sure how the listener/callback combination works. Can you pass values out of the callback function? So far I've gotten it to work with global variables, but I would rather not use global variables.
% start the DAQ session
s = daq.createSession('ni');
% open an analog input channel
s.addAnalogInputChannel('Dev1',0,'Voltage');
% set the sampling rate to 10 Hz and the total acquisition time to 10 s
s.Rate = 20;
s.DurationInSeconds = 10;
% set the 'DataAvailable' event to trigger after 200 samples?? (all samples)
s.NotifyWhenDataAvailableExceeds = 200;
% add a listener to execute function getData when 'DataAvailable' triggers?
lh = s.addlistener('DataAvailable', @getData);
% define global variables time and data
global time;
global data;
% trigger the acquisition
s.startBackground
% getData function - I don't understand the arguments, and I haven't been able to pass any outputs so far
function getData(src,event)
plot(event.TimeStamps, event.Data)
% set the global time and data variables to pass data out of the callback function
global time;
time = event.TimeStamps;
global data;
data = event.Data;
end
  2 Comments
javier coronado  bautista
javier coronado bautista on 24 Feb 2016
clc close all%limpia todo las ventas abiertar clear all%borra las variales del espacio de trabajo tic s = daq.createSession('ni');%inicializacion sesion con la finalidad de realizar la daquision de datos %d=daq.getDevices%obtenemos las caracteristicas del NI USB 6210 %d(1) %samplingRate=2000; %numberofSamples=200;%nuemero de muestras
s.Rate = 200;% frecuencia de muestreo=Fs %ai = s.inputSingleScan() %leemos las entradas de los canales analogicas a NI USB 6210 %m= fopen('event.Data','w'); %excelFileName= 'samplemalaga'; s.DurationInSeconds = 40;%definimos el tiempo de la adquisicion ch=s.addAnalogInputChannel('coronado','ai0', 'Voltage');% ch.Range=[-5 5]; ch.Name='CANAL C0' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) s.NumberOfScans %Numero de exploraciones para la operacion cuando se inicia sesion ch=s.addAnalogInputChannel('coronado','ai1', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C1' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) ch=s.addAnalogInputChannel('coronado','ai2', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C2' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) ch=s.addAnalogInputChannel('coronado','ai3', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C3' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) %s.NumberOfScans %Numero de exploraciones para la operacion cuando se inicia sesion %s.addAnalogInputChannel('coronnel('coronado','ai7', 'Voltage'); %s.addAnalogInputChannel('coronado','ai8', 'Voltage'); %s.addAnalogInputChannel('coronado','ai9', 'Voltage') %s.NumberOfScans = 2000 %Número de exploraciones para la operación cuando se inicia [data,timestamps,triggerTime] = s.startForeground();% startForeground %devuelve los datos de varias exploraciones adquiridos en una matriz mxn, donde m nuemero de exploracionesy nu numero de canales %ai = s.inputSingleScan() %leemos solo una exploracion de todos los 4 canales "C0,C1,C2,C3" de toda las exploraciones %Para adquirir varias exploraciones mediante operaciones temporizadas , véase % startForeground %d=daq.getDevices%obtenemos las caracteristicas del NI USB 6210 %d(1) %set(ai,'triggerFcn',{@mycalback,nado','ai4', 'Voltage'); %s.addAnalogInputChannel('coronado','ai5', 'Voltage'); %s.addAnalogInputChannel('coronado','ai6', 'Voltage'); %s.addAnalogInputCha %obj2mfile(ai,'myai.m'); %created:d\v6\myfiles\myai.m %created:d\v6\myfiles\myai.mat %m= fopen('event.Data','w'); %ch.InputType='SingleEnded'%Ajustar en modo referencia a masa| %Añadir un oyente con una llamada a la función anónima %lh = s.addlistener('DataAvailable', @getData);
lh = s.addlistener('DataAvailable',... @(src,event) plot(event.TimeStamps, event.Data));% creamos un oyente
%Adquirir datos s.NotifyWhenDataAvailableExceeds = 200;% frecuencia con la que el evento DataAvaialble se dispara s.startBackground();% la adquision de datos se realiza en el fondo s.IsLogging % ans = true ;esta adquiriendo datos,false=no adquiere dato %s.ScansAcquired %pause(5); s.wait() % m= fopen('event.Data','w'); %s.IsContinuous = true;% signal analog %s.startBackground() %data = getdata(ai); % comienza %s.stop; delete(lh); %fclose(m); % n = fopen('event.Data','r'); %[data,count] = fread(n,[3,inf],'double');
s.IsNotifyWhenDataAvailableExceedsAuto = true; lh = s.addlistener('DataAvailable', @stopWhenExceedOneV);%configurar nuevo oyente para procesar los datos entrantes type('stopWhenExceedOneV.m') %lh=s.addlistener('DataAvailable',... % @(getData) getData(src,event) );
%filename='event.Data' %save(filename) s.IsContinuous = true; %signal digital s.startBackground() %s.ScansAcquired%Número de exploraciones obtenida durante la operación %while s.IsRunning %pause(0.01) %fprintf('While loop: Scans acquired = %d\n', s.ScansAcquired) %end fprintf('Acquisition has terminated with %d scans acquired\n', s.ScansAcquired); disp('Acquiring data...'); disp('Acquisition complete.'); title('BRAIN UNFV-FIEI-PERÚ','color','red') % n = fopen('event.Data','r'); %[data,count] = fread(n,[3,inf],'double') xlabel('Time (segundos)'); ylabel('Voltage') Stop = 1; uicontrol('style','pushbutton','String','start',... 'Callback','Stop = 0;'); delete(lh)
%axis([0 40 -5 5 ]) toc% empleamos tic-toc para calcular el timpo de adquision
%mkdir('SESIONES/prueba'); %addpath ( 'SESIONES /prueba / myfiles' ) %prueba= 'test.mat'; %save(prueba)
%[stat,struc] = fileattrib; %PathCurrent = struc.Name; % guardar figura en la carpeta
% guardar workspace en la carpeta
%set(ai,'SampleRate',SampleRate); %set(ai,'SamplesPerTrigger',duration*SampleRate); %set(ai,'TriggerType','Manual'); %s.Rate = 8000; %s.DurationInSeconds = 1; %[ai,triggerTime] = s.startForeground(); %plot(triggerTime,ai); % Update the title of the graph %set(titleHandle,'String',['Discrete Fourier Transform Plot (fft),Number of callback function calls: ', num2str(count)]);
%%rtwintgt -install %rtwintgt -uninstall %rtwintgt -version %rtwho
%rtwintgt -setup installs the Real-Time Windows Target kernel on your system. It performs the same operation as rtwintgt -install.
%rtwintgt -install installs the Real-Time Windows Target kernel on your system. It performs the same operation as rtwintgt -setup. On Windows Vista™ and Windows® 7 systems, rtwintgt -install requires User Account Control (UAC) to be enabled.
%rtwintgt -uninstall removes the Real-Time Windows Target kernel from your system. On Windows Vista and Windows 7 systems, rtwintgt -uninstall requires User Account Control (UAC) to be enabled.
%rtwintgt -version displays the Real-Time Windows Target currently installed on your system
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ahi esta el codigo completo...
An Nguyen
An Nguyen on 14 Mar 2020
Did you ever find a solution your problem? I'm also looking to do the same thing...

Sign in to comment.

Answers (1)

javier coronado  bautista
javier coronado bautista on 24 Feb 2016
ahi les dejo elalgoritmo que los va permitir adquirir datos en tiempo real, empleando la targeta de adquision NI USB6210 . esto funciona perfectamente en sistemas de 64 bit (laptos). en la version de matlab 2015b saludos.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %d=daq.getDevices%obtenemos las caracteristicas del NI USB 6210 %d(1) %samplingRate=2000; %numberofSamples=200;%nuemero de muestras
s.Rate = 200;% frecuencia de muestreo=Fs %ai = s.inputSingleScan() %leemos las entradas de los canales analogicas a NI USB 6210 %m= fopen('event.Data','w'); %excelFileName= 'samplemalaga'; s.DurationInSeconds = 40;%definimos el tiempo de la adquisicion ch=s.addAnalogInputChannel('coronado','ai0', 'Voltage');% ch.Range=[-5 5]; ch.Name='CANAL C0' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) s.NumberOfScans %Numero de exploraciones para la operacion cuando se inicia sesion ch=s.addAnalogInputChannel('coronado','ai1', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C1' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) ch=s.addAnalogInputChannel('coronado','ai2', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C2' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) ch=s.addAnalogInputChannel('coronado','ai3', 'Voltage'); ch.Range=[-5 5]; ch.Name='CANAL C3' ch.InputType='SingleEnded';%Ajustar en modo referenciado a masa (RSE) %s.NumberOfScans %Numero de exploraciones para la operacion cuando se inicia sesion %s.addAnalogInputChannel('coronnel('coronado','ai7', 'Voltage'); %s.addAnalogInputChannel('coronado','ai8', 'Voltage'); %s.addAnalogInputChannel('coronado','ai9', 'Voltage') %s.NumberOfScans = 2000 %Número de exploraciones para la operación cuando se inicia [data,timestamps,triggerTime] = s.startForeground();% startForeground %devuelve los datos de varias exploraciones adquiridos en una matriz mxn, donde m nuemero de exploracionesy nu numero de canales %ai = s.inputSingleScan() %leemos solo una exploracion de todos los 4 canales "C0,C1,C2,C3" de toda las exploraciones %Para adquirir varias exploraciones mediante operaciones temporizadas , véase % startForeground %d=daq.getDevices%obtenemos las caracteristicas del NI USB 6210 %d(1) %set(ai,'triggerFcn',{@mycalback,nado','ai4', 'Voltage'); %s.addAnalogInputChannel('coronado','ai5', 'Voltage'); %s.addAnalogInputChannel('coronado','ai6', 'Voltage'); %s.addAnalogInputCha %obj2mfile(ai,'myai.m'); %created:d\v6\myfiles\myai.m %created:d\v6\myfiles\myai.mat %m= fopen('event.Data','w'); %ch.InputType='SingleEnded'%Ajustar en modo referencia a masa| %Añadir un oyente con una llamada a la función anónima %lh = s.addlistener('DataAvailable', @getData);
lh = s.addlistener('DataAvailable',... @(src,event) plot(event.TimeStamps, event.Data));% creamos un oyente
%Adquirir datos s.NotifyWhenDataAvailableExceeds = 200;% frecuencia con la que el evento DataAvaialble se dispara s.startBackground();% la adquision de datos se realiza en el fondo s.IsLogging % ans = true ;esta adquiriendo datos,false=no adquiere dato %s.ScansAcquired %pause(5); s.wait() % m= fopen('event.Data','w'); %s.IsContinuous = true;% signal analog %s.startBackground() %data = getdata(ai); % comienza %s.stop; delete(lh); %fclose(m); % n = fopen('event.Data','r'); %[data,count] = fread(n,[3,inf],'double');
s.IsNotifyWhenDataAvailableExceedsAuto = true; lh = s.addlistener('DataAvailable', @stopWhenExceedOneV);%configurar nuevo oyente para procesar los datos entrantes type('stopWhenExceedOneV.m') %lh=s.addlistener('DataAvailable',... % @(getData) getData(src,event) );
%filename='event.Data' %save(filename) s.IsContinuous = true; %signal digital s.startBackground() %s.ScansAcquired%Número de exploraciones obtenida durante la operación %while s.IsRunning %pause(0.01) %fprintf('While loop: Scans acquired = %d\n', s.ScansAcquired) %end fprintf('Acquisition has terminated with %d scans acquired\n', s.ScansAcquired); disp('Acquiring data...'); disp('Acquisition complete.'); title('BRAIN UNFV-FIEI-PERÚ','color','red') % n = fopen('event.Data','r'); %[data,count] = fread(n,[3,inf],'double') xlabel('Time (segundos)'); ylabel('Voltage') Stop = 1; uicontrol('style','pushbutton','String','start',... 'Callback','Stop = 0;'); delete(lh)
%axis([0 40 -5 5 ]) toc% empleamos tic-toc para calcular el timpo de adquision
%mkdir('SESIONES/prueba'); %addpath ( 'SESIONES /prueba / myfiles' ) %prueba= 'test.mat'; %save(prueba)
%[stat,struc] = fileattrib; %PathCurrent = struc.Name; % guardar figura en la carpeta
% guardar workspace en la carpeta
%set(ai,'SampleRate',SampleRate); %set(ai,'SamplesPerTrigger',duration*SampleRate); %set(ai,'TriggerType','Manual'); %s.Rate = 8000; %s.DurationInSeconds = 1; %[ai,triggerTime] = s.startForeground(); %plot(triggerTime,ai); % Update the title of the graph %set(titleHandle,'String',['Discrete Fourier Transform Plot (fft),Number of callback function calls: ', num2str(count)]);
%%rtwintgt -install %rtwintgt -uninstall %rtwintgt -version %rtwho
%rtwintgt -setup installs the Real-Time Windows Target kernel on your system. It performs the same operation as rtwintgt -install.
%rtwintgt -install installs the Real-Time Windows Target kernel on your system. It performs the same operation as rtwintgt -setup. On Windows Vista™ and Windows® 7 systems, rtwintgt -install requires User Account Control (UAC) to be enabled.
%rtwintgt -uninstall removes the Real-Time Windows Target kernel from your system. On Windows Vista and Windows 7 systems, rtwintgt -uninstall requires User Account Control (UAC) to be enabled.
%rtwintgt -version displays the Real-Time Windows Target currently installed on your system

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!