Documentation

Using Callback Functions to Create Live Displays and Analysis

This example shows how to create a callback function for displaying event information to the MATLAB® command window and a callback function for plotting the data as it is acquired.

See also DAQHELP, DAQCALLBACK, DAQTIMERPLOT.

Note: This can only be run using the 32-bit version of MATLAB® and Data Acquisition Toolbox™. To learn more about using data acquisition devices on other platforms, see this example.

First, find any running data acquisition objects and stop them. This stops all running data acquisition objects from interfering with this example. This code is usually not necessary outside this example unless there are multiple data acquisition objects running.

if (~isempty(daqfind))
    stop(daqfind)
end

EVENTS. In general, data acquisition tasks are based on events. An event occurs at a specific time after a condition is met. The event types supported by the Data Acquisition Toolbox™ include:

  • errors

  • triggers

  • start

  • stop

CALLBACK FUNCTIONS. When an event occurs, you can execute a related function known as a callback function. A callback function is a valid MATLAB file that can perform essentially any task during your data acquisition session such as:

  • processing data

  • displaying data

  • displaying a message

A callback function is associated with an event by setting one of the callback properties to the name of the callback function. The callback properties are listed below.

ANALOG INPUT AND ANALOG OUTPUT CALLBACK PROPERTIES

 RuntimeErrorFcn       - Executes when a run-time error occurs.
 StartFcn              - Executes just prior to the device
                         and engine start.
 StopFcn               - Executes just before the device and
                         engine stop.
 TimerFcn              - Executes when the time specified by
                         TimerPeriod occurs.
 TriggerFcn            - Executes when a trigger occurs.

ANALOG INPUT CALLBACK PROPERTIES

 DataMissedFcn         - Executes when the engine misses data.
 SamplesAcquiredFcn    - Executes when the number of samples
                         specified by SamplesAcquiredFcnCount
                         is acquired.

ANALOG OUTPUT CALLBACK PROPERTIES

 SamplesOutputFcn      - Executes when the number of samples
                         specified by SamplesOutputFcnCount
                         is output.

DIGITAL I/O CALLBACK PROPERTIES

 TimerFcn              - Executes when the time specified by
                         TimerPeriod passes.

The callback function must have at least two input arguments. The first input argument is the object that caused the event to occur. The second input argument is a structure containing information regarding the event that occurred.

In the first example, let's create an analog input object that displays the type of the event and the time the event occurred to the MATLAB command window.

To begin, let's create an analog input object associated with the winsound device and containing one channel. The analog input object will be configured to acquire 8000 samples per second.

ai = analoginput('winsound');
addchannel(ai, 1);
ai.SampleRate = 8000;

The analog input object will trigger five times immediately upon start. Each trigger will acquire 8000 samples.

ai.TriggerType = 'immediate';
ai.SamplesPerTrigger = 8000;
ai.TriggerRepeat = 4;

Let's create the callback function, daqcallback.m, which displays the event and time of the event to the MATLAB command window.

type daqcallback
function daqcallback(obj, event)
%DAQCALLBACK Display event information for the specified event.
%
%    DAQCALLBACK(OBJ, EVENT) a callback function which displays a 
%    message which contains the type of the event and the name 
%    of the object which caused the event to occur.  If an error
%    event occurs, the time of the event and the error message 
%    is also displayed.
%
%    By default, an analog input object's DataMissedFcn and 
%    RuntimeErrorFcn properties are set to @daqcallback and an 
%    analog output object's RuntimeErrorFcn property is set to 
%    @daqcallback.
%
%    If the event type is DataMissed, the object is stopped. 
%
%    DAQCALLBACK should only be used as a property value for a
%    callback property.  To display event information on an object,
%    SHOWDAQEVENTS should be used.
%
%    Example:
%      ai = analoginput('winsound');
%      addchannel(ai, 1);
%      ai.TriggerFcn = @daqcallback;
%
%    See also DAQHELP, PROPINFO, SHOWDAQEVENTS, DEMODAQ_CALLBACK.
%

%    MP 9-21-98
%    Copyright 1998-2012 The MathWorks, Inc.

% Define error message.
error1 = 'Type ''daqhelp daqcallback'' for an example using DAQCALLBACK.';

switch nargin
case 0
   error('daq:daqcallback:argcheck', 'This function may not be called with 0 inputs.\nType ''daqhelp daqcallback'' for an example using DAQCALLBACK.');
case 1
   error('daq:daqcallback:argcheck', error1);
case 2
   if ~isa(obj, 'daqdevice') || ~isa(event, 'struct')
      error('daq:daqcallback:argcheck', error1);
   end   
   if ~(isfield(event, 'Type') && isfield(event, 'Data'))
      error('daq:daqcallback:argcheck', error1);
   end
end
  

% Determine the type of event.
EventType = event.Type;

switch lower(EventType)
case {'start', 'trigger', 'stop', 'timer', 'samplesacquired', 'samplesoutput', 'error'}
   % Determine the time of the error event.
   EventData = event.Data;
   EventDataTime = EventData.AbsTime;
   
   % Convert the clock time to a datenum so that it can be converted to the
   % display string.
   EventDataTime = num2cell(EventDataTime);
   EventDataTime = datenum(EventDataTime{:});

   % Create a display indicating the type of event, the time of the event and
   % the name of the object.
   fprintf([EventType ' event occurred at ' datestr(EventDataTime,13),...
         ' for the object: ' obj.Name '.\n']);

   %fprintf('Milliseconds: %f\n', EventData.AbsTime(6) - floor(EventData.AbsTime(6)) );
   
   % Display the error string.
   if strcmp(lower(EventType), 'error')
      fprintf([EventData.String '\n']);
   end
case 'datamissed'
   % Create a display indicating the type of event and the name of the 
   % object.
   fprintf([EventType ' event occurred for the object: ' obj.Name '.\n']);
   stop(obj)
otherwise
   % Create a display indicating the type of event and the name of the 
   % object.
   fprintf([EventType ' event occurred for the object: ' obj.Name '.\n']);
end




The analog input object is configured to display the start, trigger, and stop events to the MATLAB Command Window.

ai.StartFcn = @daqcallback;
ai.StopFcn = @daqcallback;
ai.TriggerFcn = @daqcallback;

The analog input object is then started, and we'll wait for up to 6 seconds for the acquisition to complete.

start(ai)
wait(ai,6);
Start event occurred at 14:54:58 for the object: winsound0-AI.
Trigger event occurred at 14:54:58 for the object: winsound0-AI.
Trigger event occurred at 14:54:59 for the object: winsound0-AI.
Trigger event occurred at 14:55:00 for the object: winsound0-AI.
Trigger event occurred at 14:55:01 for the object: winsound0-AI.
Trigger event occurred at 14:55:02 for the object: winsound0-AI.
Stop event occurred at 14:55:03 for the object: winsound0-AI.

In the second example, let's create an analog input object that plots data as it is being acquired.

Let's configure the analog input object, ai, to collect data for five seconds immediately upon start.

ai.TriggerType = 'immediate';
ai.SamplesPerTrigger = 40000;
ai.TriggerRepeat = 0;

Let's create the callback function, daqtimerplot.m, which plots the data as it is being acquired.

type daqtimerplot
function daqtimerplot(obj, event)
%DAQTIMERPLOT Plots the data acquired.
%
%    DAQTIMERPLOT(OBJ, EVENT) plots the data acquired by the data
%    acquisition engine.  This is an example callback function for the
%    TimerFcn property and is used by the demodaq_callback example.  
%
%    DAQTIMERPLOT can be used with any analog input object.
%
%    Example:
%      ai = analoginput('winsound');
%      addchannel(ai, 1);
%      ai.SamplesPerTrigger = 40000;
%      ai.TimerFcn = @daqtimerplot;
%      start(ai);
%
%    See also DEMODAQ_CALLBACK. 
%

%    Copyright 1998-2010 The MathWorks, Inc.

if nargin == 0 
   error(['This function may not be called with 0 inputs.\n',...
         'Type ''daqhelp daqtimerplot'' for an example using DAQTIMERPLOT.']);
elseif nargin == 1
   error('Type ''daqhelp daqtimerplot'' for an example using DAQTIMERPLOT.');
end

% Determine the number of samples to plot.  Make sure that we never try to
% get more samples than are available in the engine.
size = min(floor((obj.SampleRate)*(obj.TimerPeriod)),obj.SamplesAvailable);

% Preview the data in the data acquisition toolbox buffer, and plot it.
data = peekdata(obj, size);
plot(data);
drawnow;


Finally, let's configure the analog input object to plot the data every 0.1 seconds.

ai.TimerPeriod = 0.1;
ai.TimerFcn = @daqtimerplot);
ai.StartFcn ='';
ai.StopFcn ='';
ai.TriggerFcn = '';

% The analog input object is started.  Wait for up to 6 seconds for the
% acquisition to complete
start(ai)
wait(ai,6);

It is possible to pass additional input arguments to your callback function. For example, if the function was called mycallback.m and you wanted to pass the arguments, range1 and range2 to the function, the callback property would be defined as follows:

   ai.TriggerFcn = {@mycallback, 'range1', 'range2'}

And the callback function would have the following function line:

   function mycallback(obj, event, range1, range2)

Lastly, delete the analog input object.

delete(ai);
Was this topic helpful?