Modelling of mechatronic system in Matlab/SimMechanics

16
Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.cz Faculty of Mechanical Engineering, Brno University of Technology Page 1 Building a GUI in MATLAB Robert Grepl Institute of Solid Mechanics, Mechatronics and Biomechanics Faculty of Mechanical Engineering, Brno University of Technology 2013-2016 Outline GUI with GUIDE [MA60] GUI programmatically figure, uicontrol callbacks How to organize GUI and data/model? Sine wave example - Nested function approach [MA71] Sine wave example - MVC approach [MA72] Combination of GUIDE and programmatic approach www.mechlab.cz ISMMB, Faculty of Mechanical Engineering, Brno University of Technology 2

Transcript of Modelling of mechatronic system in Matlab/SimMechanics

Page 1: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 1

Building a GUI in MATLAB

Robert GreplInstitute of Solid Mechanics, Mechatronics and Biomechanics

Faculty of Mechanical Engineering, Brno University of Technology

2013-2016

Outline

GUI with GUIDE [MA60]

GUI programmatically figure, uicontrol

callbacks

How to organize GUI and data/model?

– Sine wave example - Nested function approach [MA71]

– Sine wave example - MVC approach [MA72]

Combination of GUIDE and programmatic approach

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

2

Page 2: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 2

Outline

Creating a GUI

–1] with GUIDE– 2] programmatically

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

3 www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

4

What is GUIDE?

„GUIDE, the MATLAB graphical user interface development environment, provides a set of tools for creating graphical user interfaces (GUIs).

These tools greatly simplify the process of designing and building GUIs. „ [help]

Page 3: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 3

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

5

Intro

GUI = Graphical User Interface

GUI consists of: Layout

o visual components (buttons, graphs, menus, …)

o stored in FIG file

Program

o stored in M file

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

6

How to start with GUIDE

type guide

or click File/New/GUI

Page 4: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 4

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

7

GUIDE: Layout editor and components

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

8

Programming GUI using GUIDE

Callback = function that is executes in response to some action by the user (event). this is named “event-driven programming”

event = mouse click, menu item selection, typing value,…

Callback’s skeleton is generated automatically by GUIDE. example: function that is called after the click on the button

useful icon

Page 5: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 5

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

9

hObject, handles

hObject = handle to current component

handles = structure with objects (handles) of all components

How to get/set properties?

… also you can set/get properties of other component:

function pushbutton1_Callback(hObject, eventdata, handles)

….

myStr = get(hObject,'String')

set(hObject,'String','My button')

set(handles.edit1,'String','1234')

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

10

Exchange data within GUI – globals and UserData property

GUI programm consists of several functions (callbacks)

Each function has its own workspace.

How to exchange data between functions?

(global variables) – not very recommended programming techniques

UseData Property – „All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property's value, but only one value can exist at a time. „

function edittext1_Callback(hObject, eventdata, handles)

mystring = get(hObject,'String'); % get string after edit

string_history{end+1} = mystring; % save string into a cell array

set(hObject,'UserData', string_history); % store it in UserData

end

function pushbutton1 _Callback(hObject, eventdata, handles)

string_history = get(handles.edittext1,'UserData'); % get history

....... % use string history somehow...

end

Page 6: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 6

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

11

Exchange data within GUI - Handles

How to exchange data between functions?

(global variables) – ...

UseData Property – ...

Store user data in handles

handles.MyUserDataInHandles = ...;

% Update handles structure

guidata(hObject, handles);

:: Laboratory of mechatronics :: Faculty of Mechanical Engineering :: Brno University of

Technology ::

MA 60: Storing user data in handles structure

TASK:

Use GUIDE to create a GUI with 3 push buttons, edit box and Static text.

SAVE: this button must store stringsin “memory”

SHOW button shows all stored strings

CLEAR button clears the history.

handles.MyStringHistory{...} = ...

Page 7: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 7

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

13

How to assign a variable to base workspace?

PROBLEM: We need to define a variable in base (main) workspace (e.g. to beused as a parameter in Simulink).

SOLUTION:

assignin('base',‘x',x);

Outline

Creating a GUI – 1] with GUIDE

– 2] programmatically

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

14

Page 8: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 8

Intro

If created with GUIDE, GUI consists of: [MA70]– FIG-file

– m-file.

If programmatically, everything is in m-file(s).

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

15

hFig = figure('Position',[100 100 300 250],...

'Menubar','none');

hText = uicontrol('Parent',hFig,...

'Style','text',...

'String','...',...

'Position',[50 100 200 100]);

hButton = uicontrol('Parent',hFig,...

'Style','pushbutton',...

'String','My button! ',...

'Position',[50 50 200 100],...

'Callback',...

'set(hText,''String'',[''Random number is: '', num2str(rand)]) ');

Agenda for Programmatic GUI

figure, uicontrol

callbacks

How to organize GUI and data/model?

Combination of GUIDE and programmatic approach

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

16

Page 9: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 9

figure, uipanel, uitab

figure, uipanel

axes

uitabgroup, uitab(introduced in R2014b)[MA74]

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

17

% Requires MATLAB R2014b and higher.

hFig = figure('Menubar','none','Position',[50 50 500 400]);

hPanel = uipanel('Parent',hFig,'BackgroundColor','white',...

'Position',[0 0 0.5 1]);

hTabgp = uitabgroup(hPanel,'Position',[.05 .05 0.9 .9]); % R2014b

hTab1 = uitab('Parent',hTabgp, 'Title', 'Tab nr. 1'); % R2014b

hTab2 = uitab('Parent',hTabgp, 'Title', 'Tab nr. 2'); % R2014b

hAxes = axes('Parent',hFig, 'Position',[0.55 0.1 0.4 .8])www.mechlab.cz

ISMMB, Faculty of Mechanical Engineering, Brno University of Technology18

position property

Property ‘position‘ requires a vector of 4 lengths:o Distance from the right edge of the figure

o Distance from the buttom edge of the figure

o Width of the object

o Height of the object

Can be defined in different units Default units are pixels

Normalized units are useful.

Example uicontrol( 'style' , 'text' , 'string' , 'Example', 'position', [50 50 100 100])

Page 10: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 10

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

19

uicontrol

hObject = uicontrol( ‘PropertyName‘ , ‘PropertyValue‘, ...)

Creates a control object (push button, edit button, text, etc.) in curently focused figure.

Optionaly outputs handle to the control object.

hText = uicontrol( 'style','text',...

'string', 'This is a label.',...

'units', 'normalized' ,...

'position', [0.1 0.6 0.25 0.1] ,

'FontSize', 20 );

hButton = uicontrol( 'style','pushbutton',...

'string', 'PushMe',...

'units', 'normalized' ,...

'position' , [0.65 0.6 0.25 0.1],...

'callback' , 'set(Text1,''string'',''Done'')');

uitable

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

20

Page 11: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 11

Callbacks

What Is a Callback? [help „Write Code for Callbacks“]

A callback is a function that you write and associate with a specific component in the GUI or with the GUI figure itself.

The callbacks control GUI or component behavior by performing some action in response to an event for its component.

The event can be a mouse click on a push button, menu selection, key press, etc.

This kind of programming is often called event-drivenprogramming.

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

21

Callbacks

Kinds of Callbacks [help „Write Code for Callbacks“]

Callback Control action. Executes, for example, when a user clicks a push button or selects a menu item.Components: Context menu, user interface controls

KeyPressFcnExecutes when the user presses a keyboard key and the callback's component or figure has focus.Components: Figure, user interface controls.

... for more see [help „Write Code for Callbacks“].

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

22

Page 12: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 12

Callbacks

Specify Callbacks in Function Calls A string that contains one or more MATLAB or toolbox commands to

evaluate

A handle to a function that is within scope when the GUI is running

A cell array containing a string function name or a function handle, plus optional strings, constants, or variable names for arguments

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

23

How to organize a GUI ? – Nested functions

This is not a trivial task...

Mathworks says [help Create and Run a Programmatic GUI] : include everything in one file:

This approach can be used, especially in case of small projects.

Nested functions can be usedto simplify the code. [MA71]

However: the problem (model, data) is not separated from GUI.

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

24

function varargout = mygui(varargin)

% MYGUI Brief description of GUI.

% Comments displayed at the

command line in response

% to the help command.

% (Leave a blank line following the

help.)

% Initialization tasks

% Construct the components

% Initialization tasks

% Callbacks for MYGUI

% Utility functions for MYGUI

end

Page 13: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 13

:: Laboratory of mechatronics :: Faculty of Mechanical Engineering :: Brno University of

Technology ::

MA 71: Controlling frequency of sine wave

TASK:

Create GUI programmatically axes

slider

Use “Nested Function” approach

Use line function to plot data.

Use OnSlide function to update XData and YDataof the line (using set).

stackoverflow.com :: What's the “right” way to organize GUI code?

[http://bit.ly/1YCDcDh]

I disagree that MATLAB is not good for implementing (even complex) GUIs - it's perfectly fine.However, what is true is that:

o There are no examples in the MATLAB documentation of how to implement or organize a complex GUI application

o All the documentation examples of simple GUIs use patterns that do not scale well at all to complex GUIs

o In particular, GUIDE (the built-in tool for auto-generating GUI code) generates terrible code that is a dreadful example to follow if you're implementing something yourself.

Because of these things, most people are only exposed to either very simple or really horrible MATLAB GUIs, and they end up thinking MATLAB is not suitable for making GUIs.

In my experience the best way to implement a complex GUI in MATLAB is the same way as you would in another language - follow a well-used pattern such as MVC (model-view-controller).

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

26

Page 14: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 14

How to organize a GUI ? – MVC

MVC = Model – View – Controlleris a software architectural pattern for implementing user interfaces on computers. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. [wiki MVC]

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

27

Required functionality:

– MODEL: based on parameters f (frequency) and a (amplitude) creates sine wave signal

– CONTROLLER: f can be changed using slider

– VIEW: sine wave is plotted

Implementation:

– MODEL:

» stores properties, calculates sine wave

» if f changed, a message is sent to VIEW

– CONTROLLER:

» main app. which creates model object and view object

» define a callback function for Slider (on change of Slider, f is changed in model object)

– VIEW:

» creates complete GUI

» listen to MODEL and if f changed, redraw the plot

Example [MA72] based on [bit.ly/1YCDcDh].

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

28

MA 72: Controlling frequency of sine wave II.

Page 15: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 15

Combination of GUIDE and programmatic approach

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

29

hFig = hgload('my_GUIDE_figure.fig');

% extract handles to GUI components

hAx = findobj(hFig, 'tag','axes1');

hButton1 = findobj(hFig, 'tag','pushbutton1');

hButton2 = findobj(hFig, 'tag','pushbutton2');

hButton3 = findobj(hFig, 'tag','pushbutton3');

set(hButton1,'Callback','set(hButton1,''BackgroundColor'',''red'')')

1. Create GUI with GUIDE.

2. Load FIG in your code.

Example [MA73] based on [bit.ly/1YCDcDh].

Useful commands

alignAlign user interface controls (uicontrols) and axes.

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

30

Page 16: Modelling of mechatronic system in Matlab/SimMechanics

Robert Grepl, MechLab - Mechatronics Laboratory, www.mechlab.czFaculty of Mechanical Engineering, Brno University of Technology Page 16

www.mechlab.czISMMB, Faculty of Mechanical Engineering, Brno University of Technology

31

References

[wiki MVC] https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

[bit.ly/1YCDcDh] http://stackoverflow.com/questions/20064610/whats-the-right-way-to-

organize-gui-code/20078237#20078237 , http://bit.ly/1YCDcDh

www.mechlab.czInstitute of Solid Mechanics, Mechatronics and Biomechanics

Faculty of Mechanical EngineeringBrno University of Technology

Contakt: assoc. prof. Robert Grepl, [email protected], tel.: +420 5114 288