| Contents | Index |
| On this page… |
|---|
View and Run the GUIDE Timer GUI Components Used by the Timer GUI |
This example shows how to refresh a display by incorporating a timer in a GUI that updates data. Timers are MATLAB objects. Programs use their properties and methods to schedule tasks, update information, and time out processes. For example, you can set up a timer to acquire real-time data at certain intervals, which your GUI then analyzes and displays.
The GUI displays a surface plot of the peaks function and contains 3 uicontrols:
The Start Randomizing push button — Starts the timer running, which executes at a rate determined by the slider control. At each iteration, random noise is added to the surface plot.
The Stop Randomizing push button — Halts the timer, leaving the surface plot in its current state until you click the Start Randomizing button again.
The Timer Period slider — Speeds up and slows down the timer, changing its period within a range of 0.01 to 2 seconds.
The following illustrations show the GUI. The left shows the initial state of the GUI. The right shows the GUI after running the timer for 5 seconds at its default period of 1 count per second.
|
|
This example contains links to a FIG-file and a code file that MATLAB documentation provides. If you use the MATLAB Help browser to view the example, the links will be active and you can access the files. If you are reading this example on the Web or in PDF form, find this topic in the MATLAB Help Browser to use the links.
To modify the layout or code of this GUI example, first save copies of its code file and FIG-file to your current folder. (You need write access to your current folder to do this.)
Type guide ex_guide_timergui in the Command Window or click here to open the GUI in GUIDE.
Open the GUI code file, ex_guide_timergui.m, from GUIDE or click here to open the GUI code file in the Editor.
You can view the properties of any component by double-clicking the component in the Layout Editor, which opens the Property Inspector for it. You can modify the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as. This saves both files, allowing you to rename them, if you choose.
Caution Only rename GUIDE GUIs from within GUIDE. Renaming GUIDE files from a folder window or the command line prevents them from operating properly until you restore their original names. |
If you just want to run the GUI or inspect it in GUIDE, follow these steps:
Click here to add the examples folder to the MATLAB path (only for the current session).
Click here to display the GUI in the GUIDE Layout Editor (read only).
Click here to display the GUI code file in the MATLAB Editor (read only)
Caution Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. |
The timer GUI has nine components within its figure window. Five components are static text uicontrols used as labels. The following table describes the five active components. To view a callback in the Editor, click the link in the Callback column. You cannot access the timer object from within GUIDE; it is created programmatically.
| Component | Tag | Description | Callback |
|---|---|---|---|
| push button | startbtn | Starts/resumes timer that adds noise to the surface plot, | startbtn_ Callback |
| push button | stopbtn | Halts timer to stop plot from updating. | stopbtn_ Callback |
| axes | display | Displays a changing surface plot. | n/a |
| slider | periodsldr | Changes period of timer between its Min of 0.01 s., and its Max of 2 s., and updates a label displaying the period value. | periodsldr_ Callback |
| timer | timer | An object that keeps time by executing a callback when each period elapses, | update_ display |
The components have tags, strings, and positions specified in GUIDE, but are not otherwise modified.
The GUI also has opening and closing functions containing user code:
ex_guide_timergui_OpeningFcn — Creates the timer object and initializes the slider andthe slider label.
figure1_CloseRequestFcn — Stops and destroys the timer object, and then destroys the figure.
Each callback in the GUI either creates, modifies, starts, stops, or destroys the timer object. The following sections describe what the callbacks do.
ex_guide_timergui_OpeningFcn creates the timer using the following code:
handles.timer = timer(...
'ExecutionMode', 'fixedRate', ... % Run timer repeatedly
'Period', 1, ... % Initial period is 1 sec.
'TimerFcn', {@update_display,hObject}); % Specify callbackThe opening function also initializes the slider Min, Max, and Value properties, and sets the slider label to display the value:
set(handles.periodsldr,'Min',0.01,'Max',2)
set(handles.periodsldr,'Value',get(handles.timer('Period'))
set(handles.slidervalue,'String',...
num2str(get(handles.periodsldr,'Value')))A call to surf renders the peaks data in the axes, adding the surfaceplot handle to the handles structure:
handles.surf = surf(handles.display,peaks);
Finally, a call to guidata saves the handles structure contents:
guidata(hObject,handles);
startbtn_Callback calls timer start method if the timer is not already running:
if strcmp(get(handles.timer, 'Running'), 'off')
start(handles.timer);
end
stopbtn_Callback calls the timer stop method if the timer is currently running:
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
endperiodsldr_Callback is called each time you move the slider. It sets timer period to the slider current value after removing unwanted precision:
% Read the slider value
period = get(handles.periodsldr,'Value');
% Timers need the precision of periods to be greater than about
% 1 millisecond, so truncate the value returned by the slider
period = period - mod(period,.01);
% Set slider readout to show its value
set(handles.slidervalue,'String',num2str(period))
% If timer is on, stop it, reset the period, and start it again.
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
set(handles.timer,'Period',period)
start(handles.timer)
else % If timer is stopped, reset its period only.
set(handles.timer,'Period',period)
endThe slider callback must stop the timer to reset its period, because timer objects do not allow their periods to vary while they are running.
update_display is the callback for the timer object. It adds Gaussian noise to the ZData of the surface plot:
handles = guidata(hfigure); Z = get(handles.surf,'ZData'); Z = Z + 0.1*randn(size(Z)); set(handles.surf,'ZData',Z);
Because update_display is not a GUIDE-generated callback, it does not include handles as one of its calling arguments. Instead, it accesses the handles structure by calling guidata. The callback gets the ZData of the surface plot from the handles.surf member of the structure. It modifies the Z matrix by adding noise using randn, and then resets the ZData of the surface plot with the modified data. It does not modify the handles structure.
Note Nothing prevents you from adding the handles structure as an argument to a non-GUIDE-generated callback, such as update_display. However, the handles data the callback receives is a static copy which does not change when other parts of your code update handles by calling guidata. For this reason, the update_display callback calls guidata to get a fresh copy of handles each time it executes. |
MATLAB calls the figure1_CloseRequestFcn when you click the close box of the GUI. The callback cleans up the application before it exits, stopping and deleting the timer object and then deleting the figure window.
% Necessary to provide this function to prevent timer callback
% from causing an error after GUI code stops executing.
% Before exiting, if the timer is running, stop it.
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
end
% Destroy timer
delete(handles.timer)
% Destroy figure
delete(hObject);In addition to acquiring or processing data at regular intervals, you can use timers to implement other time-based procedures in a GUI:
Time-limit extended computations
Time-out pending connections
Start and stop simulations
Poll sets of devices
Administer tests
For more information about programming timers in GUIs, see Control Program Execution Using Timer Objects. For details about timer properties, methods, and events, see Using a MATLAB Timer Object and the timer reference page.
![]() | Use a Modal Dialog Box to Confirm an Operation (GUIDE) | Create GUIs Programmatically | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |