Reputation: 13
I am tring to make a function in MATLAB that can take in different arguments like a timer. Something like
function timercommand(arg)
if arg == go
for t = 1:100
pause (1)
if arg == stop
...
Something like that. But I want to be able to call it like: timercommand(go)
and later call timercommand(stop)
. But I really don't know how to do it.
I need the function to be able to Count down towards 0. If it reaches zero it should set itself to 'Stopped' and I have to be able to recognize that it has done that.
I also need to be able to stop the countdown myself to prevent it from activating other functions that I want to use together with this function.
As an example off what I am trying to (just an example off use) do is that I want to issue a reboot on my computer. I need the reboot to happen in a certain time if I do not respond or have enough time to halt it.
Hope that makes my question more understandable. Sorry for any confusion!
Upvotes: 1
Views: 1150
Reputation: 13933
Just use a timer
-object. It already does exactly what you want. Here is an example to start the timer with start(T)
and stop the timer with stop(T)
. The stop
-command is commented out to test the behaviour. Before we can start the timer, we have to set some parameters like StartDelay
for the time to wait (here 5 seconds) and the TimerFcn
that gets called once the timer is done.
function TimerMain
T = timer; % Create a timer object
set(T,'StartDelay',5); % Specify the time to wait
set(T,'TimerFcn',@TimerCallback); % Assign a callback-function
start(T); % Start the timer
%stop(T); % Stop the timer
%delete(T); % Delete the object if no longer needed
end
function TimerCallback(~,~) % Gets called when timer is done
disp('Reboot in progress!');
end
Note that instead of using the set
-commands you can directly assign them when you call timer
like this: T = timer('StartDelay',5,'TimerFcn',@TimerCallback);
Upvotes: 2
Reputation: 98
When you call your function timercommand(arg)
you're out of the main function and while your timercommand
is running your main would be at the same point. Event if you use command arg == stop
your code will work only after the timercommand(arg)
.
The answer depends of your wanted result.
For example for measure time between two clicks on button you can use event handlers (http://www.mathworks.com/help/matlab/matlab_external/using-events.html#responsive_offcanvas).
If you describe your problem with more details maybe somebody will help you.
Good luck!
Upvotes: 0
Reputation: 149
I would do something like this (the definition of t, the timer, is outside the main function so if you copy and paste it in matlab it won't work, but you should define consequently with the rest of your program):
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
'StartDelay',1);
function timercommand(arg)
switch arg
case 'go'
start(t)
case 'stop'
stop(t)
end
I hope this helps!
Upvotes: 0