How to create a stopwatch

5 visualizzazioni (ultimi 30 giorni)
Renato Pereira
Renato Pereira il 15 Lug 2017
Commentato: Walter Roberson il 22 Lug 2017
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!

Risposte (1)

Walter Roberson
Walter Roberson il 16 Lug 2017
The timerfcn should be given as @stopwatch
  2 Commenti
Renato Pereira
Renato Pereira il 22 Lug 2017
Still not working :(
Walter Roberson
Walter Roberson il 22 Lug 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

Accedi per commentare.

Categorie

Scopri di più su Code Execution in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by