How do I pass variables between timer callback functions?

4 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2014 年 11 月 5 日
編集済み: MathWorks Support Team 2021 年 10 月 26 日
I have a timer and I initialise data in the StartFcn callback and manipulate that data in my TimerFcn callback. However, these callbacks have different scopes, and each time the TimerFcn is evaluated the workspace is cleared.
Is there a way of passing data between my StartFcn callback and the TimerFcn callback? And how can I have my TimerFcn manipulate the same variables each time without having to use persistent variables?

採用された回答

MathWorks Support Team
MathWorks Support Team 2021 年 10 月 22 日
編集済み: MathWorks Support Team 2021 年 10 月 26 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

タグ

タグが未入力です。

製品


リリース

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by