How to create a stopwatch
5 views (last 30 days)
Show older comments
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!
0 Comments
Answers (1)
Walter Roberson
on 16 Jul 2017
The timerfcn should be given as @stopwatch
2 Comments
Walter Roberson
on 22 Jul 2017
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
See Also
Categories
Find more on Code Execution in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!