Delay function to slow down while loop

13 views (last 30 days)
Edward Lau
Edward Lau on 19 Nov 2017
Answered: Walter Roberson on 19 Nov 2017
Hey guys. I'm new to MATLAB and I've got a question to ask. I am currently doing up this UI which includes a code which is shown below.
% --- 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)
global s brightness a t;
t = 0.1
a = 1;
readasync(s);
while (a == 1)
brightness = str2double(fscanf(s, '%s', 8));
set(handles.brightness, 'String', num2str(brightness));
disp(brightness);
if brightness < 87
if brightness < 44
fprintf(s, '%s',1);
else
fprintf(s,'%s',2);
end
else
if brightness < 130
fprintf(s, '%s',3);
else
fprintf(s, '%s',4);
end
end
if(a==0)
break;
end
pause(1/10);
end
As you can see, I am currently using a pause function to delay the while loop. However my mentor in college suggested that I use tic toc instead of pause to delay the loop. I do not know how should I go about with it. He has given me this function but I do not know how to implement it. Any advice?
function delay(t)
tic;
while toc < t
end
end

Answers (1)

Walter Roberson
Walter Roberson on 19 Nov 2017
pause() is the better choice. It gives a chance for other things to happen, and it gives up control of the CPU so it does not need to run as hot. Using tic/toc requires continuous computation. Please see https://en.wikipedia.org/wiki/Busy_waiting

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!