MATLAB: Problem with togglebutton callback

togglebuttontogglebutton callback

This is the code of the two togglebuttons which i created in guide. when i press the first togglebutton i activate the second one too, however the code in the first togglebutton isn't executed.
After i call the
togglebutton2_Callback(handles.togglebutton2, eventdata, handles)
nothing appears at the edit1 as i expect.
The code in button2 runs normally and i see the results at edit2.
function togglebutton1_Callback(hObject, eventdata, handles)
ispushed=get(hObject,'Value');
if ispushed
set(hObject, 'String', 'STOP');
else
set(hObject, 'String', 'START');
end
set(handles.togglebutton2, 'Value', 1);
togglebutton2_Callback(handles.togglebutton2, eventdata, handles)
x=0;
set(handles.edit1, 'String', x);
function togglebutton2_Callback(hObject, eventdata, handles)
tic;
while get(hObject,'Value')
b=toc;
set(handles.edit2, 'String', floor(b));
drawnow
end
What am i doing wrong?
And one more question, how do i stop the execution of the code in button2 by pressing the button1?

Best Answer

alex - look closely at the code in your togglebutton1 callback
set(handles.togglebutton2, 'Value', 1);
togglebutton2_Callback(handles.togglebutton2, eventdata, handles)
x=0;
set(handles.edit1, 'String', x);
You set the string for the button and then call the callback for togglebutton2 which includes a while loop. And so long as the condition of the while loop is true, we will never exit the togglebutton2_Callback function and control will never return to togglebutton1_Callback...which means that x never gets initialized and the edit1 control never gets updated. So you probably want to do this before calling the other function.
I don't understand the purpose of the second toggle button. Why is it necessary if the first toggle button starts the counter? Would the user ever push the second toggle button callback? If absolutely necessary, then you could modify your code to be as follows
function togglebutton1_Callback(hObject, eventdata, handles)
ispushed=get(hObject,'Value');
if ispushed
set(hObject, 'String', 'STOP');
x=0;
set(handles.edit1, 'String', x);
set(handles.togglebutton2, 'Value', 1);
togglebutton2_Callback(handles.togglebutton2, eventdata, handles)
else
set(hObject, 'String', 'START');
set(handles.togglebutton2,'Value',0);
end
The above is similar to what you have shown. Note that in the body of the else we set the Value property to zero for the second toggle button so that we exit from the while loop in its callback.
You may want to reconsider some of this code. Ask yourself if the second toggle button is necessary and how you may just use the first one to control the updates to the edit boxes.