Showing posts with label GUI. Show all posts
Showing posts with label GUI. Show all posts

Saturday, August 31, 2013

MATLAB GUI and Timer Object

I shouldn't really started this post at all since I have little time to 'beautify' the post, but what's described in this post can be very useful for someone that needs to have the GUI update itself at a fixed time interval, say, plotting the latest forecast data. Note that it doesn't have to be a fixed timer interval, in fact if you put enough thought into this, the schedule for the updates can be very flexible (by using database, etc).

Be warned though, the quality of the post is lacking, but I will make sure the sample application is running as expected so all you need to do is to expand on it and plug in all the pieces you need/have.

If you are not familiar with MATLAB GUI, you should read up on it (and unfortunately this post is probably not for you). If you are fairly familiar with MATLAB GUI, but haven't used  the timer object much. Here is the documentation, it is best if you try out a few examples that uses timer object without the GUI, just to get a feel for it.

Now, without further ado, below is a walk through of creating a MATLAB GUI-based digital clock (from scratch).

1. Type GUIDE in matlab, and choose to create a blank gui.

2. Create a static text on the GUI, make it and its fontsize big, and tag it as lbl_timeNow

3. Save the GUI (with the name, say, myClock), and open up its m-file.

4. In the OpeningFcn (prefixed with whatever name), insert the following code

timer_obj = timer(...
    'StartFcn',         @user_timer_start, ...              % start function
    'TimerFcn',         {@user_timer_update, hObject}, ...  % timer function, has to specific the handle to the GUI,
    'StopFcn',          @user_timer_stop, ...               % stop function
    'ErrorFcn',         @user_timer_err, ...                % error function
    'ExecutionMode',    'fixedRate', ...                    %
    'Period',           0.1, ...                           % updates every xx seconds
    'TasksToExecute',   inf, ...
    'BusyMode',         'drop');


start(timer_obj);        % start the timer object

setappdata(hObject, 'timer_obj', timer_obj');  % save the timer object as app data

Effectively, we just created and started a timer whose TimerFcn gets executed every 0.1 second. And the timer is saved as the app data so when we try to close the GUI, we can easily get our hands on the timer and get rid of it at the same time. 

5. Implement the user_timer_update function (which is set as the TimerFcn of the timer). Insert the following function to the m file. Notice how it has three input parameters, the last of which was past in in step 5 with '{@user_timer_update, hObject},'.

function user_timer_update(src,evt, fig_handle)

handles = guihandles(
fig_handle);

set(handles.lbl_timeNow, 'string', datestr(now, 'yyyy-mm-dd HH:MM:SS'));


6. Put in the other timer functions, StartFcn, StopFcn, ErrorFcn into the m file. They are just dump text printer for now. 

function user_timer_start(src, evt)
disp('Timer started!');

function user_timer_stop(src, evt)
disp('Timer stop');

function user_timer_err(src, evt)
disp('Timer error');


7.  We are almost done, just need to make sure the timer is removed when we close the GUI. So go to the GUIDE editor, and select 'CloseRequestFcn' property of the figure, it should populate the function in the m file for you. Now, before delete(hObject), put in

stop(getappdata(hObject, 'timer_obj')); % stops the timer 
delete(getappdata(hObject, 'timer_obj'));  % delete the timer object 

8. Now, here is a list of things that you may want to do: 

  • make the gui look pretty 
  • properly implement the other timer functions, StartFcn, StopFcn, etc. 


Here is what it looks like and here are .fig and .m files. 



Well. That's all for now. Good luck. 

Saturday, April 21, 2012

Detecting the type of mouse click

There are many ways for a user to interact with application using a mouse, there are normal click (single left click) that often selects the object, single right click that often opens up a context menu, and double-left click that often opens up the object. The ability to detect the type of the mouse click will come in handy when you are developing a truly interactive GUI. Fortunately, such information can be easily obtained by extracting the information stored in the SelectionType property of the GUI, which is a figure object.

1. Create a blank GUI and save the files.

2. Create a function to be attached to the WindowButtonDownFcn property of the GUI.


function winButtonDownFcn(hObject, eventData) 
m_type = get(hObject, 'selectionType');
if strcmp(m_type, 'normal')
    fprintf('left mouse click\n');
elseif strcmp(m_type, 'alt')
    fprintf('right mouse click\n'); 
elseif strcmp(m_type, 'open')
    fprintf('double-click\n');
end

3. In the opening function of the GUI, attach the function to the WindowButtonDownFcn property of the GUI.

set(hObject, 'windowButtonDownFcn', @winButtonDownFcn);

4. Running the GUI and try out different type of mouse clicks, the corresponding detection should be printed in the command window.

Note that there are other mouse clicks and/or key pressed may result in the same values in the selectionType property, for example, Control+left click will show up as a right click. If you would like to implement the more complicated mouse clicks (with key pressed), be sure to check the table in the documentation.

Example can be download here.

Thursday, January 26, 2012

Signals Virtual Lab (SVL) Suite demo (advanced)

A demo video is shown below to put the potentials of the SVL suite into prospective. The video shows the SVL suite being used in examining the signals sampling and reconstruction. One major improvement when compare to the SVL suite's first release is the fact that users can draw connections between devices as if they were using Simulink, however, the customized characteristics of the individual GUI remains. In other words, the SVL suite utilizes the connection functionality of Simulink, but retains the same GUI for each device.

In the video, the function generator output is fed to a signal splitter, with one splitter output going to the oscilloscope, and the other going into the sampling box. One by one, the sampling waveform and the sampled signal are examined using the oscilloscope. To reconstruct the original signal, the sampled signal then goes through a low-pass filter. Spectrum of the various signals are observed.

Note that as long as the function generator and oscilloscope are used, any Signals lab can be transformed into the virtual lab if the corresponding signal processing components are created.




Tuesday, January 24, 2012

MATLAB GUI: Tracking mouse actions

In the second tutorial of the series, we will look at how we can track the mouse actions such as pressing and releasing. We will start with the GUI we created in the first tutorial, and we will add a text field that details the last mouse action and its location.

Step-by-step guide

1. Download mouse1.zip, and ready the files in a working folder of MATLAB.
2. Open gui_mouse.fig using GUIDE.
3. Add a static text to the GUI and rename its tag to lbl_last_action
4. Open the property window of the figure (double click on the figure), click on WindowButtonDownFcn to populate the callback and paste the following code:
    pos = get(hObject, 'currentpoint'); % get mouse location on figure
    x = pos(1); y = pos(2); % assign locations to x and y
    set(handles.lbl_last_action, 'string', ['Mouse pressed @ X: ', num2str(x), ', Y: ', num2str(y)]);
5. Click on WindowButtonUpFcn to populate the callback and paste the following code: 
    pos = get(hObject, 'currentpoint'); % get mouse location on figure
    x = pos(1); y = pos(2); % assign locations to x and y
    set(handles.lbl_last_action, 'string', ['Mouse released @ X: ', num2str(x), ', Y: ', num2str(y)]);
6. Press F5 (or click on run button) to start up the GUI.

Anytime when the mouse is pressed (down) or released (up), the text field is updated with the action and the location of the action. Note that if the button is released quickly after pressed, the text field may be updated too quickly as if there is no press action.

Video 


Files: 

Files can be downloaded here. Note some changes have been made to the GUI to make it more presentable.

MATLAB GUI: inserting background image to push/toggle button

This is a brief tutorial on how to insert background image to push button and toggle button in MATLAB GUI. The idea is simple, read in the background image as a matrix, and then assign the matrix to CData property to the buttons.

1. Create a new GUI in MATLAB using GUIDE, and save the file.
2. Add uicontrols push button (or toggle button), rename their tag as pb (or tb).
3. In the OpeningFcn in the corresponding m-file, copy and paste the following code:

bg_image = imread('button.jpg');
set(handles.pb_with_bg, 'CData', bg_image);

Note, you may want to set pixel as the figure's unit so that you can easily figure out the size of the button that will show you the entire background image. In other words, the size of the button and the size of the background image should match.  


Video


Files
Source files can be download here.

Saturday, January 21, 2012

MATLAB GUI: Tracking mouse locations


In the first part of the series, we will create a simple GUI that will show the current position of the mouse on the GUI.

Step-by-step guide:
  1. Create new GUI using MATLAB GUIDE, save file as gui_mouse
  2. Create two static text fields and configure them as fellow
    1. rename tags to lbl_x and lbl_y
    2. set strings to 'x loc:' and 'y loc:'
    3. set FontSize to 18, and resize components 
  3. Configure figure property (double-click on figure)
    1. rename tag to fig_mouse
    2. change unit to pixels
    3. click on callback for WindowButtonMotionFcn and insert the following code
    pos = get(hObject, 'currentpoint'); % get mouse location on figure
    x = pos(1); y = pos(2); % assign locations to x and y
    set(handles.lbl_x, 'string', ['x loc:' num2str(x)]); % update text for x loc
    set(handles.lbl_y, 'string', ['y loc:' num2str(y)]); % update text for y loc 


  4. Save all files and run the GUI or M-file.
Note: anytime the mouse is moved over the GUI, it will trigger the WindowButtonMotionFcn on the figure, which will then update the labels with the current location of the mouse pointer on the figure. 

Video:




Files:

Download source files here

Friday, January 20, 2012

MATLAB GUI tutorial planned


I am planning to create a tutorial series on how to incorporate mouse movements and actions into MATLAB GUI. Traditionally, the GUIs are designed to accept user input via a variety of uicontrols (or components). While having the components are sufficient in most applications, there are still cases where the user experience may be drastically enhanced by utilizing mouse movements and actions.

The end-product of the series is a GUI that allows user dragging and dropping an object in the GUI. The series will contain a number of tutorials, each dealing with a specific subject (or sub-problem). Each tutorial will be built on the earlier tutorials, either provides a different functionality or a more advance usage of the same functionality (or both).

The series of tutorials may cover the following topics (subject to change)

Thursday, January 19, 2012

SVL Suite V1.0.0 available for download

My submission of SVL Suite to MATLAB Central File Exchange was rejected. The reason for the rejection is because my submission contains p-files. Having the p-files, which hides the source code, kind of defeats the purpose of File Exchange, which is to allow users to learn from each other by looking at the source code. It is fair, but I wish they had spelled it out in their Guidelines for New Submissions.

In any case, I believe SVL suite is a very useful application/learning tool and I am determined to at least try to give it a bit of exposure on the Internet. And therefore, I updated the project website I created for the SVL Suite (in 2010), and package up the first release for download. I also submitted the link of the project website to the Link Exchange on MATLAB Central. Let's see where it takes us. 




Tuesday, January 10, 2012

Auto- and Cross-correlation demo in MATLAB

Purpose of the GUI is to help readers visualize the auto- and cross-correlation of discrete time signals.

A screenshot of the cross-correlation demo using MATLAB GUI

How to use:
  1. Download MATLAB files from here.
  2. In MATLAB, navigate to the folder where the files are stored 
  3. Type gui_xcorr and hit Enter. 

Acceptable formats as input discrete-time signals:
  • An array, such as [3, 2, 1, 5] or cos(2*pi*0.02*(0:99))]
  • A 2-row matrix with the top row storing sample indices and the bottom row storing sample data, such as [0:3; 3 2 1 5] or [0:99; cos(2*pi*0.02*(0:99))]