Stop an infinite loop with a key

3 次查看(过去 30 天)
Hey guys, I have this infinite loop and I want to exit the while loop and continue the code when I press the cancel button in the waitbar, but this button isnt working, what can I do?
% Start the module
dev.start();
fprintf('Start of LimeSDR\n');
tic;
start_time=datetime('now','Format','dd-MMM-uuuu HH:mm:ss.SSS');
hWaitbar = waitbar(0,'Receiving Samples', 'Name', 'Progress', ...
'CreateCancelBtn','setappdata(gcbf,''canceling'',1)');
setappdata(hWaitbar,'canceling',0);
while true
% Receive samples on RX1 channel
indRx1 = 1; % index of the last received sample
[samples1, ~, samplesLength1] = dev.receive(Fs*Ts,1);
bufferRx1(indRx1:indRx1+samplesLength1-1) = samples1;
TT=array2timetable(samples1,'SampleRate',Fs,'StartTime',start_time);
writetimetable(TT,'Timetable_Rx1.txt','Delimiter','bar');
type Timetable_Rx1.txt
pause(1);
if getappdata(hWaitbar,'canceling')
% Stop the if cancel button was pressed
disp('Stopped by user');
break;
end
delete(hWaitbar);
end
% Cleanup and shutdown by stopping the RX stream and having MATLAB delete the handle object.
dev.stop();
tempo_rececao=toc;
stop_time=datetime('now','Format','dd-MMM-uuuu HH:mm:ss.SSS');
clear dev;
fprintf('Stop of LimeSDR\n');

采纳的回答

Jan
Jan 2022-6-22
编辑:Jan 2022-6-22
You delete the waitbar in the first iteration:
delete(hWaitbar);
Remove this line. or move it behind the loop.
I cannot imagine what you call "does not work", because if you delete the complete waitbar, there is no button to press at all. Maybe you have some orphaned waitbars from former trials?
  2 个评论
Miguel Albuquerque
Miguel Albuquerque 2022-6-22
I get this bar, I ve also deleted the line. But when I say it doesn't work, it means when I press cancel button, the while loop doesnt stop.
delete(hWaitbar);
Jan
Jan 2022-6-23
Explaining, what does not happen, is less useful thanto explain what is happening.
if getappdata(hWaitbar,'canceling')
Does this stop with an error, because there is no field "canceling" before you press the button?
Defining callbacks as CHAR vectors is not recommended. Such strings are evaluated in the base workspace. If you have redefined e.g. "gcbf" as a variable, the callback will fail. Prefer function handles:
hWaitbar = waitbar(0,'Receiving Samples', 'Name', 'Progress', ...
'CreateCancelBtn', @(h, e) setappdata(ancestor(h, 'figure'), canceling', 1));

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by