MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

t = timer('TimerFcn',@(x,y)disp('Hello World!'),'StartDelay',5);


NoteWhen you specify the callback commands directly as the value of the callback
function property, the commands are evaluated in the MATLAB workspace.


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 a MATLAB program file and specify the 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 character vector that identifies the type of event that
caused the callback. The value of this field can be any of the following: '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” on page 27-
8.


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 character vector and includes this text in the display output. To see this
function used with a callback property, see “Specifying the Value of Callback Function
Properties” on page 27-8.


function my_callback_fcn(obj, event, text_arg)


txt1 = ' event occurred at ';
txt2 = text_arg;


event_type = event.Type;
event_time = datestr(event.Data.time);


Timer Callback Functions
Free download pdf