As described in our Timer Callback documentation here:
timer callbacks need their function declaration in the form:
function processing(src, event)
The "src" variable is actually the timer object that calls the callback. The TIMER class has a property called "UserData" which you can set to whatever value you want. If you have a lot of data you want to pass between functions, you could set this to be a structure or cell array containing all the variables you need to pass around.
See:
Here is some example code demonstrating this process:
function MakeTimer()
t=timer;
t.StartFcn = @initTimer;
t.TimerFcn = @timerCallback;
t.Period = 0.5;
t.TasksToExecute = 5;
t.ExecutionMode = 'fixedRate';
start(t);
wait(t);
delete(t);
end
function initTimer(src, event)
src.UserData = 0;
disp('initialised')
end
function timerCallback(src, event)
src.UserData = src.UserData + 1;
disp(src.UserData)
end
This will output:
>> MakeTimer
initialised
1
2
3
4
5
Another option, would be to make the callbacks nested functions of MakeTimer. Nested functions use the same workspace as the parent function, so all variables are accessible.
See:
Here is an example of using nested functions as timer callbacks:
function MakeTimer()
myVar = [];
t=timer;
t.StartFcn = @initTimer;
t.TimerFcn = @timerCallback;
t.Period = 0.5;
t.TasksToExecute = 5;
t.ExecutionMode = 'fixedRate';
start(T);
wait(T);
delete(T);
function initTimer(src, event)
myVar = 0;
disp('initialised')
end
function timerCallback(src, event)
myVar = myVar + 1;
disp(myVar)
end
end
Best Answer