Handles not getting updated from pushbutton using GUIDE

1 view (last 30 days)
Hello Everyone,
For my own understanding, I am trying to create a simple counter GUI with 2 pushbuttons namely 'Start counting' and 'Stop counting'
Start counting - Starts the counter
Stop counting - Stops the counter
I am having troubles to Stop the running counter using the Stop pushbutton. For some reason the handles.stop which gets set to 1 in the StopCounter_Callback does not reflect in the StartCounter_Callback.
Here is the piece of code.
Any help will be much appreciated. Thanks in advance.
function StartCounter_Callback(hObject, eventdata, handles)
counter = 0;
handles.start = 1;
while (1)
guidata(hObject, handles);
if (handles.stop == 0)
counter = counter + 1;
myString = sprintf('Value is %d', counter);
set(handles.text1, 'String', myString);
drawnow;
pause(0.1);
else
% Reset the Start & Stop button
handles.stop = 0;
handles.start = 0;
return;
end
end
% --- Executes on button press in StopCounter.
function StopCounter_Callback(hObject, eventdata, handles)
if(handles.start == 1)
handles.stop = 1;
end
guidata(hObject, handles);

Accepted Answer

Rik
Rik on 10 Aug 2021

Your looping function doesn't store the modified handle struct.

guidata(hObject, handles);
%put this before your return statement 
  1 Comment
Pratik Chachad
Pratik Chachad on 10 Aug 2021
Hello @Rik Thanks for your response. I think I found the answer. The issue was that I was not retriving the updated elements from handles structure.
"handles = guidata(handles.figure1);"
My updated code is here. Everything works now as expected. Thanks.
function StartCounter_Callback(hObject, eventdata, handles)
% Run the loop once, if start is already running do nothing
if(handles.start == 0)
handles.start = 1;
%save the data
guidata(hObject, handles);
counter = 0;
while (handles.start)
handles = guidata(handles.figure1);
if (handles.stop == 0)
counter = counter + 1;
myString = sprintf('Value is %d', counter);
set(handles.text1, 'String', myString);
drawnow;
else
% Reset the Start & Stop button
handles.stop = 0;
handles.start = 0;
%save the data
guidata(hObject, handles);
end
end
end
function StopCounter_Callback(hObject, eventdata, handles)
% hObject handle to StopCounter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if(handles.start == 1)
handles.stop = 1;
end
guidata(hObject, handles);

Sign in to comment.

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!