Count the time a toggle button is pressed down

Hello,
I would like to know how can I create a timer that will only be activated when a toggle button is pressed down. It will of course start from 0 as the button is up when I launch the GUI, but when I press the button, I would like the timer to start, and then stop when I press it again. Then, I would like the timer to resume when I press the toggle button down again, and so on.
How can I do that?
Thanks!

回答 (1 件)

Andrew Reibold
Andrew Reibold 2014 年 12 月 2 日
編集済み: Andrew Reibold 2014 年 12 月 2 日

0 投票

I use tic and toc to start and stop timers
>> help tic
tic Start a stopwatch timer.
tic and TOC functions work together to measure elapsed time.
Run tic and a timer starts. Then everytime you run toc , it tells you how much time since the last tic.
What I would do is run tic and toc to measure how long the toggle was down. Save that value to a variable. Then each time you do that another time, add the new tic/toc difference to your running variable of total time.

3 件のコメント

Andrew Reibold
Andrew Reibold 2014 年 12 月 2 日
編集済み: Andrew Reibold 2014 年 12 月 2 日
The reason your code in the other answer doesn't work is because your while loop never 'ends'. So your function starts, enters the while loop, then it keeps running tic infinite times and never displays toc. Eventually you try to press the button again but you are still stuck in the while loop from the first time.
If your functions are interruptable then it might cancel your function without ever finishing it.
Also, don't put 'tic' in the while loop. Each time tic runs it restarts your timer. I'm not sure if that will be beneficial for you in your case.
Lets test something. What happens if you do this
function togglebutton1_Callback(hObject, eventdata, handles)
if get(hObject, 'Value')
tic
disp('timer started')
else
toc
disp(['time elapsed = ',num2str(toc)])
end
Let me know what happens. My only concern is that when the function runs a second time you lose your workspace tic/toc values or something.
Guillaume
Guillaume 2014 年 12 月 2 日
編集済み: Guillaume 2014 年 12 月 2 日
To make sure that you don't 'lose your workspace tic/toc values or something' and to make sure that a tic/toc from another piece of code does not interfere, explicitly use the return value of tic:
function togglebutton1_Callback(hObject, eventdata, handles)
persistent t;
if get(hObject, 'Value')
t = tic
disp('timer started')
else
elapsedtime = toc(t);
fprintf('time elapsed = %f', elapsedtime);
end
end
Andrew Reibold
Andrew Reibold 2014 年 12 月 2 日
Nice Guillaume.
Any updates Matt..?

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

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

質問済み:

2014 年 12 月 2 日

コメント済み:

2014 年 12 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by