Kết nối Matlab Gui và Matlab Simulink

Matlab là bộ công cụ hỗ trợ rất tốt cho các ứng dụng kỹ thuật, bộ công cụ Simulink hỗ trợ lập trình mô phỏng có thể kết nối với Matlab Gui (Graphic User Interface). Trước khi bắt tay vào thực hiện một ví dụ đơn giản về kết nối Matlab Simulink và Matlab Gui thì hãy xem một project phức tạp mà mình đang thực hiện

https://www.youtube.com/watch?v=gJ3SwlaiIJE

Còn đây là bài hướng dẫn đơn giản nhất

  1. Tạo một mô hình Simulink đơn giản.

matlab gui control simulink

  1. Tạo một giao diện điều khiển.

matlab gui control simulink

Tóm tắt code:

% Simple Demo connect Malab Simulink and Matlab Gui
% https://bmshop.vn
% Trang web cua Tien Anh
%%
function varargout = ControlPanel(varargin)
% CONTROLPANEL MATLAB code for ControlPanel.fig
% CONTROLPANEL, by itself, creates a new CONTROLPANEL or raises the existing
% singleton*.
%
% H = CONTROLPANEL returns the handle to a new CONTROLPANEL or the handle to
% the existing singleton*.
%
% CONTROLPANEL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CONTROLPANEL.M with the given input arguments.
%
% CONTROLPANEL('Property','Value',...) creates a new CONTROLPANEL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ControlPanel_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ControlPanel_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES</code>

% Edit the above text to modify the response to help ControlPanel

% Last Modified by GUIDE v2.5 07-Nov-2014 17:27:59

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @ControlPanel_OpeningFcn, ...
'gui_OutputFcn', @ControlPanel_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin &amp;&amp; ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before ControlPanel is made visible.
function ControlPanel_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to ControlPanel (see VARARGIN)

% Choose default command line output for ControlPanel
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ControlPanel wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = ControlPanel_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

function txtLoadfile_Callback(hObject, eventdata, handles)
% hObject handle to txtLoadfile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of txtLoadfile as text
% str2double(get(hObject,'String')) returns contents of txtLoadfile as a double

% --- Executes during object creation, after setting all properties.
function txtLoadfile_CreateFcn(hObject, eventdata, handles)
% hObject handle to txtLoadfile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc &amp;&amp; isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in btnBrowse.
function btnBrowse_Callback(hObject, eventdata, handles)
% hObject handle to btnBrowse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[input_file,pathname] = uigetfile( ...
{'*mdl','mdl Files (*.mdl)';...
'*.*', 'All Files (*.*)'}, ...
'Select files', ...
'MultiSelect', 'on');
if pathname == 0
return
end
%gets the current data file names inside the listbox
inputfile = fullfile(pathname,input_file);
current_folder = strcat(cd,'');
mdlname = strrep(inputfile,current_folder,'');
mdlname = strrep(mdlname,'.mdl','');
%updates the gui to display all filenames in the listbox
set(handles.txtLoadfile,'String',mdlname);
guidata(hObject, handles);

% --- Executes on button press in btnRemove.
function btnRemove_Callback(hObject, eventdata, handles)
% hObject handle to btnRemove (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
set(handles.txtLoadfile,'String','');
guidata(hObject, handles);

% --- Executes on button press in btnLoad.
function btnLoad_Callback(hObject, eventdata, handles)
% hObject handle to btnLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global modelName
modelName = get(handles.txtLoadfile,'string');

if isempty(modelName)
errordlg('You have not input the model name');
else
set(handles.txtLcd,'string','LOADING ...');
end
guidata(hObject,handles);

% --- Executes on button press in btnStart.
function btnStart_Callback(hObject, eventdata, handles)
% hObject handle to btnStart (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
modelName = get(handles.txtLoadfile,'string');
handles.modelname = modelName;
% Load the simulink model
if ~modelIsLoaded(modelName)
load_system(modelName);
end

% Simulink may optimise your model by integrating all your blocks. To
% prevent this, you need to disable the Block Reduction in the Optimisation
% settings.
set_param(handles.modelname,'BlockReduction','off');
% When the model starts, call the localAddEventListener function
set_param(handles.modelname,'StartFcn','localAddEventListener');
% Start the model
set_param(handles.modelname, 'SimulationCommand', 'start');
set(hObject,'Enable','off');
set(handles.btnStop, 'Enable','on');
guidata(hObject,handles);

% --- Executes on button press in btnStop.
function btnStop_Callback(hObject, eventdata, handles)
% hObject handle to btnStop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

set_param(handles.modelname,'SimulationCommand','stop');
set(hObject,'Enable','off');
set(handles.btnStart,'Enable','on');
guidata(hObject,handles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for adding an event listener to the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function eventhandle = localAddEventListener

eventhandle = add_exec_event_listener('Simulink_GUI_Matlab/Gain2', ...
'PostOutputs', @localEventListener);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function to check that model is still loaded
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function modelLoaded = modelIsLoaded(modelName)
try
modelLoaded = ...
~isempty(find_system('Type','block_diagram','Name',modelName));
catch ME %#ok
% Return false if the model can't be found
modelLoaded = false;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for executing the event listener on the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function localEventListener(block, eventdata) %#ok
simData = block.OutputPort(1).Data;
display(simData);
handles = guihandles(ControlPanel) ;
set(handles.txtLcd,'string',num2str(simData(1)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Function for removing the event listener from the gain block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function localRemoveEventListener

% get the application data
ad = guidata(gcbo);

% return the startFcn to its original value
set_param(ad.modelName,'StartFcn',ad.originalStartFcn);

% delete the listener(s)
for idx = 1:length(ad.eventHandle)
if ishandle(ad.eventHandle{idx})
delete(ad.eventHandle{idx});
end
end
% remove this field from the app data structure
ad = rmfield(ad,'eventHandle');
%save the changes
guidata(gcbo,ad);

% --- Executes on button press in btnTang.
function btnTang_Callback(hObject, eventdata, handles)
% hObject handle to btnTang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

%put the value to text
set(handles.btnTang,'string','10');
%Update SIM model
set_param('Simulink_GUI_Matlab/Step','after','10');

% --- Executes on button press in btnGiam.
function btnGiam_Callback(hObject, eventdata, handles)
% hObject handle to btnGiam (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

%put the value to text
set(handles.btnTang,'string','5');
%Update SIM model
set_param('Simulink_GUI_Matlab/Gain2','Gain','5');

% --- Executes on button press in btnMode.
function btnMode_Callback(hObject, eventdata, handles)
% hObject handle to btnMode (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

[purchase_link id=“1581” style=“button” color=“blue” text=“Code Demo Matlab Gui and Simulink”]


Đăng bởi@nvtienanh
Không gì là không thể.

GitHubTwitterFacebookLinkedIn