How can I write the code of this problem of TIC /TOC timer?
3 次查看(过去 30 天)
显示 更早的评论
I want a code that is counting all the time since I press the pushbutton1. I have anothe pushbutton2 and when I press it if the time is less or equal to 3 s I want to display on a static or edit text a message, if the time is between 3s and 6s I want another message and between 6s and 20s the final message.
Could someone help me?
回答(1 个)
Jan
2017-3-28
编辑:Jan
2017-3-28
function TimingTest
H.Fig = figure;
H.Text = uicontrol('Style', 'text', 'FontSize', 20, ...
'units', 'normalized', 'Position', [0.05, 0.3, 0.9, 0.1])
Button1 = uicontrol('Style', 'PushButton', 'String', 'Start', ...
'units', 'normalized', 'Position', [0.05, 0.1, 0.35, 0.1], ...
'Callback', {@Button1CB, H});
Button2 = uicontrol('Style', 'PushButton', 'String', 'Stop', ...
'units', 'normalized', 'Position', [0.6, 0.1, 0.35, 0.1], ...
'Callback', {@Button2CB, H});
end
function Button1CB(Button1H, EventData, H)
setappdata(H.Fig, 'Started', now);
end
function Button2CB(Button1H, EventData, H)
if ~isappdata(H.Fig, 'Started')
disp('Press Start at first!');
return;
end
elapsed = (now - getappdata(H.Fig, 'Started')) * 86400;
if elapsed <= 3.0
set(H.Text, 'String', '<= 3');
elseif elapsed <= 6.0
set(H.Text, 'String', '<= 6');
elseif elapsed <= 20.0 % Or simply "else"?
set(H.Text, 'String', 'final message');
else
set(H.Text, 'String', 'too slow');
end
end
2 个评论
Jan
2017-3-28
编辑:Jan
2017-3-28
Please explain "doesn't work". Do you get an error message? If so, please post it. Perhaps the "handles" struct is incomplete? Or the "end" are missing on the functions - they are optional, but when you have one "end" to close a function, all functions need one.
I guess: "H.Fig" is undefined. Use either "handles.figure" (or how the figure handle is called. Or:
FigH = ancestor(hObject, 'figure');
elapsed = (now - getappdata(FigH, 'Started')) * 86400;
Alternatively you can store the start time in the handles struct also. Then see the many threads about sharing variables between callbacks in this forum. Search for "guidata share variable".
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!