Events and Callbacks

Events and Callbacks Basics

You can enhance the power and flexibility of your analog input application by utilizing events. An event occurs at a particular time after a condition is met and might result in one or more callbacks.

While the analog input object is running, you can use events to display a message, display data, analyze data, and so on. Callbacks are controlled through callback properties and callback functions. All event types have an associated callback property. Callback functions are functions that you construct to suit your specific data acquisition needs.

You execute a callback when a particular event occurs by specifying the name of the callback function as the value for the associated callback property. Note that daqcallback is the default value for some callback properties.

Event Types

The analog input event types and associated callback properties are described below.

Analog Input Callback Properties

Event Type

Property Name

Data missed

DataMissedFcn

Input overrange

InputOverRangeFcn

Run-time error

RuntimeErrorFcn

Samples acquired

SamplesAcquiredFcn

SamplesAcquiredFcnCount

Start

StartFcn

Stop

StopFcn

Timer

TimerFcn

TimerPeriod

Trigger

TriggerFcn

Data Missed Event

A data missed event is generated immediately after acquired data is missed. In most cases, data is missed because

  • The engine cannot keep up with the rate of acquisition.

  • The driver wrote new data into the hardware's FIFO buffer before the previously acquired data was read. You can usually avoid this problem by increasing the size of the memory block with the BufferingConfig property.

This event executes the callback function specified for the DataMissedFcn property. The default value for DataMissedFcn is daqcallback, which displays the event type and the device object name. When a data missed event occurs, the analog input object is automatically stopped.

Input Overrange Event

An input overrange event is generated immediately after an overrange condition is detected for any channel group member. An overrange condition occurs when an input signal exceeds the range specified by the InputRange property.

This event executes the callback function specified for the InputOverRangeFcn property. Overrange detection is enabled only when a callback function is specified for InputOverRangeFcn, and the analog input object is running.

Run-time Error Event

A run-time error event is generated immediately after a run-time error occurs. Additionally, a toolbox error message is automatically displayed to the MATLAB® workspace. If an error occurs that is not explicitly handled by the toolbox, then the hardware-specific error message is displayed.

This event executes the callback function specified for RuntimeErrorFcn. The default value for RuntimeErrorFcn is daqcallback, which displays the event type, the time the event occurred, the device object name, and the error message.

Run-time errors include hardware errors and time-outs. Run-time errors do not include configuration errors such as setting an invalid property value.

Samples Acquired Event

A samples acquired event is generated immediately after a predetermined number of samples is acquired.

This event executes the callback function specified for the SamplesAcquiredFcn property every time the number of samples specified by SamplesAcquiredFcnCount is acquired for each channel group member.

Use SamplesAcquiredFcn to trigger an event each time a specified number of samples is acquired. To process samples at regular time intervals, use the TimerFcn property. However, if you are performing a CPU-intensive task with the data, then system performance might be adversely affected.

Start Event

A start event is generated immediately after the start function is issued. This event executes the callback function specified for StartFcn. When StartFcn has finished executing, Running is automatically set to On and the device object and hardware device begin executing. The device object is not started if an error occurs while executing the callback function.

Stop Event

A stop event is generated immediately after the device object and hardware device stop running. This occurs when

  • The stop function is issued.

  • The requested number of samples is acquired.

  • A run-time error occurs.

A stop event executes the callback function specified for StopFcn. Under most circumstances, the callback function is not guaranteed to complete execution until sometime after the device object and hardware device stop running, and the Running property is set to Off.

Timer Event

A timer event is generated whenever the time specified by the TimerPeriod property passes. This event executes the callback function specified for TimerFcn. Time is measured relative to when the device object starts running.

Some timer events might not be processed if your system is significantly slowed or if the TimerPeriod value is too small. There can only be one timer event waiting in the queue at a given time. The callback function must process all available data to ensure that it keeps up with the inflow of data. Alternatively, you can use the SamplesAcquiredFcn (analog input) or SamplesOutputFcn (analog output) property to process the data when a specified number of samples is acquired.

Trigger Event

A trigger event is generated immediately after a trigger occurs. This event executes the callback function specified for the TriggerFcn property. Under most circumstances, the callback function is not guaranteed to complete execution until sometime after Logging is set to On.

Record and Retrieve Event Information

While the analog input object is running, certain information is automatically recorded in the EventLog property for some of the event types listed in the preceding section. EventLog is a structure that contains two fields: Type and Data. The Type field contains the event type. The Data field contains event-specific information. Events are recorded in the order in which they occur. The first EventLog entry reflects the first event recorded, the second EventLog entry reflects the second event recorded, and so on.

The event types recorded in EventLog for analog input objects, as well as the values for the Type and Data fields, are given below.

Table 7-4. Analog Input Event Information Stored in EventLog

Event Type

Type Field Value

Data Field Value

Data missed

'DataMissed'

AbsTime

RelSample

Input overrange

'OverRange'

AbsTime

RelSample

Channel

OverRange

Run-time error

'Error'

AbsTime

RelSample

String

Start

'Start'

AbsTime

RelSample

Stop

'Stop'

AbsTime

RelSample

Trigger

'Trigger'

AbsTime

RelSample

Channel

Trigger

Samples acquired events and timer events are not stored in EventLog.

    Note   Unless a run-time error occurs, EventLog records a start event, trigger event, and stop event for each data acquisition session.

The Data field values are described below.

AbsTime

AbsTime is used by the run-time error, start, stop, and trigger events to indicate the absolute time the event occurred. The absolute time is returned using the MATLAB clock format.

day-month-year hour:minute:second

Channel

Channel is used by the input overrange event and the trigger event. For the input overrange event, Channel indicates the index number of the input channel that experienced an overrange signal. For the trigger event, Channel indicates the index number for each input channel serving as a trigger source.

OverRange

OverRange is used by the input overrange event, and can be On or Off. If OverRange is On, then the input channel experienced an overrange signal. If OverRange is Off, then the input channel no longer experienced an overrange signal.

RelSample

RelSample is used by all events stored in EventLog to indicate the sample number that was acquired when the event occurred. RelSample is 0 for the start event and for the first trigger event regardless of the trigger type. RelSample is NaN for any event that occurs before the first trigger executes.

String

String is used by the run-time error event to store the descriptive message that is generated when a run-time error occurs. This message is also displayed at the MATLAB Command Window.

Trigger

Trigger is used by the trigger event to indicate the trigger number. For example, if three trigger events occur, then Trigger is 3 for the third trigger event. The total number of triggers executed is given by the TriggersExecuted property.

Retrieve Event Information

Suppose you want to examine the events logged for the example given by Voice Activation Using a Software Trigger. You can do this by accessing the EventLog property.

events = AIVoice.EventLog
events = 
3x1 struct array with fields:
    Type
    Data

By examining the contents of the Type field, you can list the events that occurred while AIVoice was running.

{events.Type}
ans = 
    'Start'    'Trigger'    'Stop'

To display information about the trigger event, you must access the Data field, which stores the absolute time the trigger occurred, the number of samples acquired when the trigger occurred, the index of the trigger channel, and the trigger number.

trigdata = events(2).Data
trigdata = 
      AbsTime: [1999 4 15 18 12 5.8615]
    RelSample: 0
      Channel: 1
      Trigger: 1

You can display a summary of the event log with the showdaqevents function. For example, to display a summary of the second event contained by the structure events:

showdaqevents(events,2)
   
2 Trigger#1           ( 18:12:05, 0 )      Channel: 1

Alternatively, you can display event summary information via the Workspace browser by right-clicking the device object and selecting Explore > Show DAQ Events from the context menu.

Create and Execute Callback Functions

When using callback functions, you should be aware of these execution rules:

  • Callback functions execute in the order in which they are issued.

  • All callback functions except those associated with timer events are guaranteed to execute.

  • Callback function execution might be delayed if the callback involves a CPU-intensive task such as updating a figure.

You specify the callback function to be executed when a specific event type occurs by including the name of the file as the value for the associated callback property. You can specify the callback function as a function handle or as a string cell array element. Function handles are described in the MATLAB documentation function_handle reference pages. Note that if you are executing a local callback function from within a file, then you must specify the callback as a function handle.

For example, to execute the callback function mycallback for the analog input object ai every time 1000 samples are acquired

ai.SamplesAcquiredFcnCount = 1000;
ai.SamplesAcquiredFcn = @mycallback;

Alternatively, you can specify the callback function as a cell array.

ai.SamplesAcquiredFcn = {'mycallback'};

Callback functions require at least two input arguments. The first argument is the device object. The second argument is a variable that captures the event information given in Table 7-4, Analog Input Event Information Stored in EventLog. This event information pertains only to the event that caused the callback function to execute. The function header for mycallback is shown below.

function mycallback(obj,event)

You pass additional parameters to the callback function by including both the callback function and the parameters as elements of a cell array. For example, to pass the MATLAB variable time to mycallback:

time = datestr(now,0);
ai.SamplesAcquiredFcnCount = 1000;
ai.SamplesAcquiredFcn = {@mycallback,time};

Alternatively, you can specify mycallback as a string in the cell array.

ai.SamplesAcquiredFcn = {'mycallback',time};

The corresponding function header is

function mycallback(obj,event,time)

If you pass additional parameters to the callback function, then they must be included in the function header after the two required arguments.

    Note   You can also specify the callback function as a string. In this case, the callback is evaluated in the MATLAB workspace and no requirements are made on the input arguments of the callback function.

Specify a Toolbox Function as a Callback

In addition to specifying your own callback function, you can specify the start, stop, or trigger toolbox functions as callbacks. For example, to configure ai to stop running when an overrange condition occurs:

ai.InputOverRangeFcn = @stop;

Use Callback Properties and Functions

This section provides examples that show you how to create callback functions and configure callback properties.

Display Event Information with a Callback Function

This example illustrates how callback functions allow you to easily display event information. The example uses daqcallback to display information for trigger, run-time error, and stop events. The default SampleRate and SamplesPerTrigger values are used, which results in a 1-second acquisition for each trigger executed.

You can run this example by typing daqdoc5_6 at the MATLAB Command Window.

  1. Create a device object — Create the analog input object AI for a sound card. The installed adaptors and hardware IDs are found with daqhwinfo.

    AI = analoginput('winsound');
    %AI = analoginput('nidaq','Dev1');
    %AI = analoginput('mcc',1);
  2. Add channels — Add one hardware channel to AI.

    chan = addchannel(AI,1);
    %chan = addchannel(AI,0); % For NI and MCC
  3. Configure property values — Repeat the trigger three times, find the time for the acquisition to complete, and define daqcallback as the file to execute when a trigger, run-time error, or stop event occurs.

    AI.TriggerRepeat = 3
    time = (AI.SamplesPerTrig/AI.SampleRate)*(AI.TriggerRepeat+1);
    AI.TriggerFcn = @daqcallback
    AI.RuntimeErrorFcn = @daqcallback
    AI.StopFcn = @daqcallback
  4. Acquire data — Start AI and wait for it to stop running. The wait function blocks the MATLAB Command Window, and waits for AI to stop running.

    start(AI)
    wait(AI,time)
  5. Clean up — When you no longer need AI, you should remove it from memory and from the MATLAB workspace.

    delete(AI)
    clear AI

Pass Additional Parameters to a Callback Function

This example illustrates how additional arguments are passed to the callback function. Timer events are generated every 0.5 second to display data using the local callback function daqdoc5_7plot (not shown below).

You can run this example by typing daqdoc5_7 at the MATLAB Command Window.

  1. Create a device object — Create the analog input object AI for a sound card. The installed adaptors and hardware IDs are found with daqhwinfo.

    AI = analoginput('winsound');
    %AI = analoginput('nidaq','Dev1');
    %AI = analoginput('mcc',1);
  2. Add channels — Add one hardware channel to AI.

    chan = addchannel(AI,1);
    %chan = addchannel(AI,0); % For NI and MCC
  3. Configure property values — Define a 10-second acquisition and execute the file daqdoc5_7plot every 0.5 seconds. Note that the variables bsize, P, and T are passed to the callback function.

    duration = 10; % Ten second duration
    AI.SampleRate = 22050
    ActualRate = AI.SampleRate;
    AI.SamplesPerTrigger = (duration*ActualRate)
    AI.TimerPeriod = 0.5
    bsize = (AI.SampleRate)*(AI.TimerPeriod);
    figure
    P = plot(zeros(bsize,1));
    T = title(['Number of callback function calls: ', num2str(0)]);
    xlabel('Samples'), ylabel('Signal (Volts)')
    grid on
    AI.TimerFcn = {@daqdoc5_7plot,bsize,P,T}
  4. Acquire data — Start AI. The drawnow command in daqdoc5_7plot forces MATLAB to update the display. The wait function blocks the MATLAB Command Window, and waits for AI to stop running.

    start(AI)
    wait(AI,duration)
  5. Clean up — When you no longer need AI, you should remove it from memory and from the MATLAB workspace.

    delete(AI)
    clear AI
Was this topic helpful?