Skip to Main Content Skip to Search
Product Documentation

Time Data Updates from a GUI (GUIDE)

About the Timer GUI Example

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 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.

View and Run the GUIDE Timer GUI

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.)

  1. Click here to copy the files to your current folder.

  2. Type guide ex_guide_timergui in the Command Window or click here to open the GUI in GUIDE.

  3. 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.

If you just want to run the GUI or inspect it in GUIDE, follow these steps:

  1. Click here to add the examples folder to the MATLAB path (only for the current session).

  2. Click here to run the ex_guide_timergui GUI

  3. Click here to display the GUI in the GUIDE Layout Editor (read only).

  4. Click here to display the GUI code file in the MATLAB Editor (read only)

Components Used by the Timer GUI

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.

ComponentTagDescriptionCallback
push buttonstartbtnStarts/resumes timer that adds noise to the surface plot,startbtn_
Callback
push buttonstopbtnHalts timer to stop plot from updating.stopbtn_
Callback
axesdisplayDisplays a changing surface plot.n/a
sliderperiodsldrChanges 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
timertimerAn 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:

How the GUI Implements the Timer

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

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 callback

The 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

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

stopbtn_Callback calls the timer stop method if the timer is currently running:

if strcmp(get(handles.timer, 'Running'), 'on')
    stop(handles.timer);
end

periodsldr_Callback

periodsldr_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)
end

The 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

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.

figure1_CloseRequestFcn

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);

Other Uses for Timers in GUIs

In addition to acquiring or processing data at regular intervals, you can use timers to implement other time-based procedures in a GUI:

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.

  


Recommended Products

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