How to implement a timer in AppDesigner

154 ビュー (過去 30 日間)
Hannes Rathmann
Hannes Rathmann 2016 年 7 月 27 日
編集済み: Adee 2023 年 9 月 23 日
Hello,
i hope somebody may can help me. I try to implement a timer (periodic 2ms) in Matlab AppDesiner (2016a). When the timer executes i will read data from a USB buffer. My problem is to set up the timer correctly so that the callback function TimerFcn is started.
Thanks
Best Regards Hannes

採用された回答

Chris Portal
Chris Portal 2016 年 8 月 5 日
編集済み: per isakson 2017 年 7 月 27 日
There are a few ways of doing this, but here's one way...
1) Create a custom property called myTimer, which would look like this:
properties (Access = private)
myTimer % Description
end
2) In your startup function, create your timer object, assign it to the custom property, and configure your timer callback. Something like this:
app.myTimer = timer('Period',2,...
'ExecutionMode', 'fixedSpacing', ...
'TasksToExecute', Inf);
app.myTimer.TimerFcn = @(x,y)disp('do something');
Note, if you need to wire your timer callback to a function inside your app, the TimerFcn syntax would be a little different. You can reference this post for a few options for that:
  6 件のコメント
Pedro Marques
Pedro Marques 2021 年 4 月 9 日
Were you able to solve this problem?
Best,
Pedro
David W Purcell
David W Purcell 2021 年 4 月 9 日
Yes. I had made some minor errors and it is working now. Thanks all for your help. David

サインインしてコメントする。

その他の回答 (1 件)

Adee
Adee 2023 年 9 月 23 日
編集済み: Adee 2023 年 9 月 23 日
The previous answer notes that "if you need to wire your timer callback to a function inside your app, the TimerFcn syntax would be a little different. You can reference this post for a few options (...)".
The refecenced post is long and It took me some experiments to find a clean way to do that, so I thought it's worth a separate answer.
The value provided for TimerFcn should be a function that accepts a timer and an event, and calls the callback method; but the callback method expects app as the first argument, so some translation is required.
In addition, the callback should be assigned separately after app has been properly created, in a startupFcn.
This can be done as follows:
properties (Access = private)
timer = timer('Name', 'App timer', 'Period', 15, 'ExecutionMode', 'fixedSpacing')
% This would create a delay of 15 seconds from end of callback invocation to next execution
end
methods (Access = private)
function timer_callback(app, timer_obj, event)
% Do whatever is needed
end
function startupFcn(app)
app.timer.TimerFcn = @(timer_obj, event) app.timer_callback(timer_obj, event);
end
end
Then, start and stop the timer using
app.timer.start;
and
app.timer.stop;
.

カテゴリ

Help Center および File ExchangeResampling Techniques についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by