How to create a stopwatch

5 ビュー (過去 30 日間)
Renato Pereira
Renato Pereira 2017 年 7 月 15 日
コメント済み: Walter Roberson 2017 年 7 月 22 日
Hey guys, I'm trying to do a GUI in which, when a button is pressed time starts to count. I created this code but when I push the button nothing happens. I think the problem is I have nested functions and they're not working. Can someone tell me the problem?
% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
c = now;
function a
a = timer('ExecutionMode','fixedRate','Period',1,'TimerFcn',@stopwatch);
start(a)
end
function stopwatch(obj,evt)
b = now;
t = b - c;
set(handles.text2,'string',datestr(t));
end
end
Thank you!

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 7 月 16 日
The timerfcn should be given as @stopwatch
  2 件のコメント
Renato Pereira
Renato Pereira 2017 年 7 月 22 日
Still not working :(
Walter Roberson
Walter Roberson 2017 年 7 月 22 日
The code
function a
a = timer('ExecutionMode','fixedRate','Period',1,'TimerFcn',@stopwatch);
start(a)
end
declares a function named 'a', and inside the function assigns a variable named 'a' a timer and starts the time, and then lets the timer go out of scope (which would delete the timer.) However, the rest of your code never calls the function 'a', so the timer is not created at all.
% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
c = now;
a = timer('ExecutionMode','fixedRate','Period',1,'TimerFcn',@stopwatch);
start(a)
handles.a = a;
guidata(hObject, handles);
function stopwatch(obj,evt)
b = now;
t = b - c;
set(handles.text2, 'string', datestr(t, 'HH:MM:SS'));
end
end

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

カテゴリ

Help Center および File ExchangeCode Execution についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by