MATLAB: Making STOP – Button

buttonguiMATLAB

Hi everybody! I'm new here and have a question about GUI's.
I have a GUI which contains (among other things) two (push)buttons. The first one is a "Start" button and the second one should be some kind of a "Stop" button. By pressing "Start" an infinite loop begins and the program starts reading a certain amount of data from a port and saves it to a file. When it finished reading it waits a few seconds and starts reading again. This happens x times, where x is a predifined value.
Now I want, that pressing the "Stop"-Button forces the program to stop at n < x runs (n depending on when I press the button).
For that purpose I defined a variable "run", which is 1 and gets 0, when "Stop" is pressed. So an exit is possible.
That's the plan. Unfortunatelly that doesn't work. I assume, that the rest of the GUI is "frozen" while the program is stuck in the loop, so pressing "Stop" doesn't change anything. I supposed pressing the button triggers some kind of interrupt, so being stuck in the loop is no problem, but sadly it seems as I am wrong (or I have to enable the interrupt, without knowing how). I already read a related post, where the questioner was advised to use a checkbox instead, but sadly this is no option for my purpose.
I hope some of you can help me? 🙂
Thank you!

Best Answer

It is hard to guess why it doesn't work without seeing any actual code. Your GUI is not frozen while your loop is running.
Small working exampel:
handles.fig=figure;
handles.pb1=uicontrol('style','pushbutton','position',[100 100 80 40],'callback',@start_cb,'string','Start');
handles.pb2=uicontrol('style','pushbutton','position',[200 100 80 40],'callback',@stop_cb,'string','Stop');
handles.run=1;
guidata(handles.fig,handles)
function start_cb(hObj,~)
while true
handles=guidata(hObj);
if handles.run==1
disp('running')
pause(1)
else
handles.run=1;
guidata(hObj,handles)
disp('stopped')
break
end
end
end
function stop_cb(hObj,~)
handles.run=0;
guidata(hObj,handles)
end