Programming Previous page   Next Page

Creating Callback Functions

When the time period specified by a timer object elapses, the timer object executes one or more MATLAB functions of your choosing. You can specify the functions directly as the value of the callback property. You can also put the commands in an M-file function and specify the M-file function as the value of the callback property.

Specifying Callback Functions Directly

This example creates a timer object that displays a greeting after 5 seconds. The example specifies the value of the TimerFcn callback property directly, putting the commands in a text string.

Putting Commands in a Callback Function

Instead of specifying MATLAB commands directly as the value of a callback property, you can put the commands in an M-file and specify the M-file as the value of the callback property.

When you create a callback function, the first two arguments must be a handle to the timer object and an event structure. An event structure contains two fields: Type and Data. The Type field contains a text string that identifies the type of event that caused the callback. The value of this field can be any of the following strings: 'StartFcn', 'StopFcn', 'TimerFcn', or 'ErrorFcn'. The Data field contains the time the event occurred.

In addition to these two required input arguments, your callback function can accept application-specific arguments. To receive these input arguments, you must use a cell array when specifying the name of the function as the value of a callback property. For more information, see Specifying the Value of Callback Function Properties.

Example: Writing a Callback Function

This example implements a simple callback function that displays the type of event that triggered the callback and the time the callback occurred. To illustrate passing application-specific arguments, the example callback function accepts as an additional argument a text string and includes this text string in the display output. To see this function used with a callback property, see Specifying the Value of Callback Function Properties.


Previous page  Associating Commands with Timer Object Events Specifying the Value of Callback Function Properties Next page

© 1994-2005 The MathWorks, Inc.