MATLAB: How to go to next loop in timer

guiMATLABtimer

Hello,
I am using a timer function to update texts on pushbuttons in my GUI. After the period of 5 seconds, the timer callback updates the text on the buttons from a matrix. I would like to go to the next loop or queue when I press any button. What should happen is that when I press a button the text on it updates along with resetting the countdown of 5 seconds. Is this possible?

Best Answer

Justin - yes, it is possible to force an update and reset the timer when the user presses any button. You just need to stop the timer, call the function to update the button text, and then restart the timer.
I noticed that all of your button callbacks are identical with the exception of setting the btn_nbr. You can create one callback that is shared amongst all push buttons by setting the Tag property of each button as
Button1 = uicontrol('Style','pushbutton','String','',...
'Position',[146, 313, 112,27],...
'Callback',@pushButtonCallback, 'Tag','1');
Button2 = uicontrol('Style','pushbutton','String','',...
'Position',[303, 313, 112,27],...
'Callback',@pushButtonCallback, 'Tag','2');
Button3 = uicontrol('Style','pushbutton','String','',...
'Position',[437, 313, 112,27],...
'Callback',@pushButtonCallback, 'Tag','3');
Button4 = uicontrol('Style','pushbutton','String','',...
'Position',[146, 245, 112,27],...
'Callback',@pushButtonCallback, 'Tag','4');
Button5 = uicontrol('Style','pushbutton','String','',...
'Position',[303, 245, 112,27],...
'Callback',@pushButtonCallback, 'Tag','5');
Button6 = uicontrol('Style','pushbutton','String','',...
'Position',[437, 245, 112,27],...
'Callback',@pushButtonCallback, 'Tag','6');
Now all pushbuttons use the same callback so we just need to update pushButtonCallback to handle the new requirements as
function pushButtonCallback(hObject,eventdata)
stop(t); % stop the timer
btn_nbr = str2double(get(hObject,'Tag')); % get the button id
pushed = 1;
updateButtonText; % update the button text
start(t); % restart the timer
end
The updateButtonText is just the body of your TimerFun callback. I did it this way because I didn't want to explicitly call the TimerFun in the above pushbutton callback. Instead the business logic has been put into updateButtonText for both functions, with
function TimerFun(hTimer,eventdata)
updateButtonText;
end
declared as above. See the attached for an updated version of your GUI.m. (Also, btn_nbr doesn't need to be declared as global.)