MATLAB: Use timer to update text in pushbutton

guiMATLABpush button

Hello,
Is there a way for a pushbutton to change its text automatically after every 5 or so seconds? My plan is to use a matrix that will contain cells of words that will be displayed onto the pushbutton. For example it will start with the word " bent" then after five seconds, it will display " went". The changing text should not be dependent on the user pressing the button. If a pushbutton is not the way to go, then can you help me with what can work? I am very new to this whole GUI idea. Also, is it better to use GUIDE or write up my own code? Thank you.

Best Answer

Justin - using GUIDE is a good way to start designing your interface. Its GUI editor allows you to drag and drop components on to the "canvas", and it provides you with many of the callbacks that you would need to respond to push button events, menu choices, etc.
For your project, you can easily use a timer to update the text of a push button or a static text control. Either would suit your needs but perhaps there is a reason why you want a push button to be used.
In the _OpeningFcn of your GUI, you could create your five second timer as
handles.timer = timer('Name','MyTimer', ...
'Period',5, ...
'StartDelay',0, ...
'TasksToExecute',inf, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@timerCallback,hObject});
% Update handles structure
guidata(hObject, handles);
% start the timer
start(handles.timer);
We save the timer handle to the handles structure in the event that we need to access it at a later time. We then start the timer (it is stopped when the GUI is closed) and rely on its callback to fire every five seconds. We define the callback as
function timerCallback(hTimer, eventdata, hFigure)
handles = guidata(hFigure);
str = handles.myCellData{handles.strIdx};
set(handles.pushbutton1,'String',str);
handles.strIdx = handles.strIdx + 1;
if handles.strIdx > length(handles.myCellData)
handles.strIdx = 1;
end
guidata(hFigure,handles);
Note the third parameter is hFigure which is the hObject from the _OpeningFcn. We use this (GUI) handle so that we can get the handles structure which contains our cell string data, the current index for where we are in the cell array, and the handles to all GUI controls (of which the pushbutton is of interest to us). We get the string, update the button text, increment the counter, and save the updated handles structure.
See the attached for an example. Try it, and see what happens!